Reputation: 353
I have many different services using spring-boot. I'd like to set up some configuration that is common for each, but allow the services to have their own properties and override them if they want. Example properties include spring.show_banner, management url ones, etc.
How can I do this? If I have the following:
I'd like them to be merged with the service1 version taking precedence. Instead, it seems that only the first one found on the classpath is used.
(Alternatively, using @Configuration classes would be even better, but I'm not sure they can be used to define many of the properties)
Upvotes: 26
Views: 28988
Reputation: 2803
I am not sure what you mean by merging them.
But I'm assuming that in the end, you are describing the situation where you have profile-specific configuration. Because, any properties that are specific to a certain service can be managed/injected using Spring profiles, which will always take precedence over default property files (see documentation).
For example, you can have the file application-service1.properties
which would automatically be used when you run your app with the property spring.profiles.active=service1
, which can be specified in the command line and other places.
If you don't specify this property, Spring Boot will fallback to the default application.properties
file.
And you can of course write the common properties in both files:
application.properties:
service.url=http://localhost:8080/endpoint
service.user=admin
service.password=admin
application-service1.properties:
service.url=http://api.service.com/endpoint
service.user=admin
service.password=aosdnoni3
Upvotes: 2
Reputation: 187
public class MyApplicationListener implements ApplicationListener<ApplicationEvent> {
@Override
public void onApplicationEvent(ApplicationEvent event) {
if (event instanceof ApplicationEnvironmentPreparedEvent) {
ApplicationEnvironmentPreparedEvent envEvent = (ApplicationEnvironmentPreparedEvent) event;
ConfigurableEnvironment env = envEvent.getEnvironment();
Properties props = new Properties();
//set props as desired
env.getPropertySources()
.addFirst(new PropertiesPropertySource("customname", props));
}
}
Then in src/main/resources/META-INF/spring.factories, add line:
org.springframework.context.ApplicationListener=mypackage.MyApplicationListener
Upvotes: 1
Reputation: 116281
There are several options available to you, all based on the order in which property sources are considered.
If your common library is responsible for creating the SpringApplication
it can use setDefaultProperties
. These values can be overridden by your services' application.properties
.
Alternatively, your library could use @PropertySource
on one of its @Configuration
classes to configure, for example, library.properties
as a source. Again, these properties could then be overriden in your services' application.properties
.
Upvotes: 33