Spring Boot command line property not overriding property defined in application.properties

chrishern picture chrishern · May 12, 2016 · Viewed 8.6k times · Source

I have created a Spring Boot app which uses a legacy library. This legacy library defines a number of Spring Beans in XML. One of which take in a property value as a constructor argument:

<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

    <bean id="myBean" class="com.em.MyBean">
        <constructor-arg name="url" value="${my.url}"/>
    </bean>
</beans>

In my Spring Boot app, I have an application.properties which defines this property as follows:

my.url=http://localhost:8080

I use the Maven Spring Boot plugin to run my app locally as follows:

mvn spring-boot:run

And the property value is injected into the bean as expected.

If I try and override the my.url property on the command line like this:

mvn spring-boot:run -Dmy.url=http://www.override.net

The overriden value is not used and instead, the value inside application.properties is used.

According to the Spring Boot docs, values from the command line should be picked up as the first priority: https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html. That does not appear to be the case here because if I remove the property from application.properties then the value passed in on the command line is used so it is not a case of the command line value being ignored altogether. It seems like the application.properties value is overriding the command line value.

Does anyone have any ideas as to what is going on?

Answer

Andy Wilkinson picture Andy Wilkinson · May 12, 2016

Using -D sets a system property. Spring Boot can consume configuration from System properties so, generally speaking, it'll work. However, it won't work if spring-boot:run is forking a separate JVM for your application as the System property will be set on the wrong JVM. As it is not working, I would guess that is what is happening.

You can use -Drun.arguments to pass arguments to the application that's being run, irrespective of whether it's run in a forked JVM. The arguments should be a comma-separated list each prefixed with --. For example, to set my.url:

mvn spring-boot:run -Drun.arguments=--my.url=http://www.override.net

The other possible cause of this problem is that your main method isn't passing the arguments that it receives into the SpringApplication that it creates. You should also check that your main method looks similar to this:

public static void main(String[] args) throws Exception {
    SpringApplication.run(YourApplication.class, args);
}

Note that args is being passed into the call to SpringApplication.run.