Reputation: 86925
How can I create a @Configuration
class that holds static inner configuration classes and inherit the @ConditionalOnProperty
?
@Configuration
@ConditionalOnProperty(value = "my.property", havingValue = "true")
public class MyConfiguration {
@Configuration
static class SubConfig1 {
}
@Configuration
static class SubConfig2 {
}
....
}
In this example, I want the inner classes to load only if the condition on the parent is true, so I don't have to repeat the condition for each config class. Is that possible?
Upvotes: 2
Views: 1698
Reputation: 40078
Your understanding is wrong on all nested classes that are annotated with @Configuration
will be loaded automatically. With nested @Configuration classes
When bootstrapping such an arrangement, only AppConfig need be registered against the application context. By virtue of being a nested @Configuration class, DatabaseConfig will be registered automatically. This avoids the need to use an @Import annotation when the relationship between AppConfig and DatabaseConfig is already implicitly clear.
So by using @ConditionalOnProperty
you can only avoid the beans that are declared in config class, but you cannot avoid the nested classes with @Configuration
annotation until specified by a condition
For Example Below approch will avoid the beans loading into ApplicationContext
if my.property
is false
@Configuration
@ConditionalOnProperty(value = "my.property", havingValue = "true")
public class MyConfiguration {
@Bean
public SubConfig1 getSubConfig1() {
return new SubConfig1();
}
@Bean
public SubConfig2 getSubConfig2() {
return new SubConfig2();
}
static class SubConfig1 {
}
static class SubConfig2 {
}
}
Upvotes: 2