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?

Eric B.
  • 23,425
  • 50
  • 169
  • 316
  • 1
    Any reason why you don't want to set it in application.properties if you want to hardcode it already? – Volker Kueffel Apr 22 '16 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. – Eric B. Apr 23 '16 at 03:37

2 Answers2

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.

Andy Wilkinson
  • 108,729
  • 24
  • 257
  • 242
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.

Kevin Page
  • 191
  • 2
  • 7
  • 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. – Eric B. Apr 23 '16 at 03:38