I have a Spring 3.1 @Configuration that needs a property foo to build a bean. The property is defined in defaults.properties but may be overridden by the property in overrides.properties if the application has an active override Spring profile.
Without the override, the code would look like this, and work...
@Configuration @PropertySource("classpath:defaults.properties") public class MyConfiguration { @Autowired private Environment environment; @Bean public Bean bean() { ... // this.environment.getRequiredProperty("foo"); ... } } I would like a @PropertySource for classpath:overrides.properties contingent on @Profile("overrides"). Does anyone have any ideas on how this could be achieved? Some options I've considered are a duplicate @Configuration, but that would violate DRY, or programmatic manipulation of the ConfigurableEnvironment, but I'm not sure where the environment.getPropertySources.addFirst() call would go.
Placing the following in an XML configuration works if I inject the property directly with @Value, but not when I use Environment and the getRequiredProperty() method.
<context:property-placeholder ignore-unresolvable="true" location="classpath:defaults.properties"/> <beans profile="overrides"> <context:property-placeholder ignore-unresolvable="true" order="0" location="classpath:overrides.properties"/> </beans> Update
If you're trying to do this now, check out Spring Boot's YAML support, particularly the 'Using YAML instead of Properties' section. The profile support there would make this question moot, but there isn't @PropertySource support yet.
Spring @Profile allow developers to register beans by condition. For example, register beans based on what operating system (Windows, *nix) your application is running, or load a database properties file based on the application running in development, test, staging or production environment.
In the application. properties we have set the local profile to be active. With the SpringApplicationBuilder's profiles method we add two additional profiles.
Add the overriding @PropertySource in a static inner class. Unfortunately, you must specify all property sources together which means creating a "default" profile as the alternative to "override".
@Configuration public class MyConfiguration { @Configuration @Profile("default") @PropertySource("classpath:defaults.properties") static class Defaults { } @Configuration @Profile("override") @PropertySource({"classpath:defaults.properties", "classpath:overrides.properties"}) static class Overrides { // nothing needed here if you are only overriding property values } @Autowired private Environment environment; @Bean public Bean bean() { ... // this.environment.getRequiredProperty("foo"); ... } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With