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.