Hello
Hello

Reputation: 403

SpringBoot SpringApplicationBuilder

I need to test my Spring application code by creating a Cucumber integration test. I am using SpringApplicationBuilder to start up my application before the actual logic is triggered and am using the following syntax to do so:-

application = new SpringApplicationBuilder()
    .parent(new Object[]{"classpath:file1.xml", "classpath:file2.xml"})
    .profiles("abc")
    .properties("name:value") [It has 5/6 (name:value) pairs here]*
    .showBanner(false)
    .logStartupInfo(true)
    .headless(true)
    .application()
    .run();

My Spring application starts up correctly. However, it does not get the values for the property (name, value) pairs that I am passing to the SpringApplicationBuilder(). I have tried the following to set them :-

  1. Using name value pairs as above
  2. List item using a HashMap of (name, value) pairs
  3. Creating a ConfigurableEnvironment, retrieving the MutablePropertySources and setting my properties in it.

None of these options are working, so when the application starts up and the code tries to access certain System Property values, it breaks.

Any ideas how this could be fixed.. All the help is greatly appreciated! I need these properties to be Spring properties to make sure the app works correctly. Maybe I can test my code using the Spring props in some other way? If so, how do I do it?

Upvotes: 2

Views: 9029

Answers (2)

Yoav Hermon
Yoav Hermon

Reputation: 1

I've dealt with the same issue myself. My problem was that the keys whose values I was trying to set were also set in an application.properties file.

After removing the entries from the file, it worked.

Upvotes: 0

Mithun
Mithun

Reputation: 8067

You can configure the properties as below:

application = new SpringApplicationBuilder()
    .parent(new Object[]{"classpath:file1.xml", "classpath:file2.xml"})
    .profiles("abc")
    .properties("key1:test1", "key2:test2") 
    .showBanner(false)
    .logStartupInfo(true)
    .headless(true)
    .application()
    .run();

Now, retrieve the properties using @Value annotation:

@Value("${key1}")
String val;

The val variable will be assigned the value test1

Upvotes: 1

Related Questions