External configuration for spring-boot application
Spring Boot offer many ways to specify the location of your properties, it´s not needed to modify your sources.
Yo can define the spring.config.location value for example:
In your
tomcat/conf/Catalina/<host>
context descriptors:<Context> <Parameter name="spring.config.location" value="/path/to/application.properties" /> </Context>
As a JVM parameter in your tomcat
setenv.sh
file:-Dspring.config.location=/path/to/application.properties
As a
SPRING_CONFIG_LOCATION
environment variable.
You're probably using external configuration in the form of application.properties
in the current directory when you're running your application as a jar. However, "current directory" isn't very useful when deploying as a war in an external tomcat. Even if you find out what the current directory is, it's most likely the same location for all applications running in that tomcat, so when you're running more than one application, that's not going to work very well.
What we do here is this declare two PropertySources
on our application:
@PropertySources({@PropertySource(value={"classpath:internal.properties"}), @PropertySource(value={"file:${application.properties}"})})
internal.properties
contains "built in" default values for propeties. The second PropertySource
is a file containing external configuration. Note how the name of the file is itself a property.
We define this externally in the Context
element of our application (in tomcat):
<Context docBase="/path/to/your/war/your.war">
<Parameter name="application.properties" value="/path/to/your/properties/application.properties"/>
</Context>
This allows you to have multiple applications running in tomcat, each application using it's own external properties file. You can even have multiple instances of the same application running with different properties.
To externalize the Spring Boot application.properties when deploying as a war file you can set spring.config.location
at the beginning when Spring Boot application is configured:
public class Application extends SpringBootServletInitializer {
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder springApplicationBuilder) {
return springApplicationBuilder
.sources(Application.class)
.properties(getProperties());
}
public static void main(String[] args) {
SpringApplicationBuilder springApplicationBuilder = new SpringApplicationBuilder(Application.class)
.sources(Application.class)
.properties(getProperties())
.run(args);
}
static Properties getProperties() {
Properties props = new Properties();
props.put("spring.config.location", "classpath:myapp1/");
return props;
}
For more details check this solution.