1

I'm probably missing something obvious, but I am trying to figure out how to set/override properties from a Spring Boot SpringApplication programatically when running the app.

By default, I know I can pass command line arguments to the boot application, but I want to embed the spring boot application in another java app, and executed from within the parent app. I've included it as a dependency to my project.

In my Spring Boot application I have the following:

static public main(String [] args){
    SpringApplication app = new SpringApplication(Sync.class);
    app.setWebEnvironment(false);
    app.setShowBanner(false);
    app.run(args);
}

This allows me to set command line arguments, such as --userName=Eric etc.

Although I realize I can technically do the same programmatically and add --userName=Eric to my args[] array in code, I figured there must be another cleaner/neater way to pass an argument/property to my app. But I cannot seem to find any other method in SpringApplication that allows me to set that type of value.

I'm looking for something that would allow me to do something like the following:

app.setProperty("username", "Eric");

Am I missing something obvious?

2
  • 1
    Any reason why you don't want to set it in application.properties if you want to hardcode it already? Commented Apr 22, 2016 at 23:47
  • I've simplified the use case a little, but the parameters are configurable in the calling app, so hard coding an application.properties file is not something I'd want to do. Commented Apr 23, 2016 at 3:37

2 Answers 2

5

When you need more control over the application that you are creating, you can use SpringApplicationBuilder and, in this case, its properties method. For example:

 new SpringApplicationBuilder(Application.class)
            .properties("foo=bar").run(args);

There are also variants that take Properties and Map.

Sign up to request clarification or add additional context in comments.

Comments

1

I'm not finding a way to modify the app arguments other than what you've suggested, but I would posit your use case fits external configuration:

https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html

If you know the values you need ahead of time, I would think the application.config file is where they should live. Then you can access them via @Value annotations etc.

1 Comment

That's just it. I don't know their cases ahead of time. The calling app is specifying the params. I'm just trying to move the param from the command line to the execution call.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.