I'm using Spring's Java-based configuration in my application. I have a root configuration class that imports a bunch of other configurations, each which may import more configurations and so on:
@Config
@Import(AnotherConfig.class)
class RootConfig {
// beans
}
@Config
@Import(YetAnotherConfig.class)
class AnotherConfig {
// beans
}
@Config
class YetAnotherConfig {
// beans
}
I then bootstrap the system by declaring a AnnotationConfigWebApplicationContext
in my web.xml
file whose contextConfigLocation
is set to RootConfig
.
Is there a way to determine the full set of configuration classes that has bootstrapped my application? Some function like this (might take a subclass for ctx
...):
List<Class> readConfigClasses(ApplicationContext ctx) {
// what goes here?
// should return [ RootConfig.class,
// AnotherConfig.class,
// YetAnotherConfig.class ]
}
Update: @axtavt's answer gets most of the way there, returning the actual configuration objects themselves, which are instances enhanced by CGLIB in my case. Grabbing the superclass of these proxies does the trick:
List<Class<?>> readConfigClasses(final ApplicationContext ctx) {
List<Class<?>> configClasses = new ArrayList<Class<?>>();
for (final Object config :
ctx.getBeansWithAnnotation(Configuration.class).values()) {
configClasses.add(config.getClass().getSuperclass());
}
return configClasses;
}
@Configuration
classes are managed by Spring like regular beans, therefore you can enumerate them as ctx.getBeansWithAnnotation(Configuration.class)
.
However, I'm not sure how would it work in complex cases (@Bean
s in non-@Configuration
classes, etc).
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