Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to enumerate Spring java configuration classes?

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;
} 
like image 664
Dan Vinton Avatar asked Nov 11 '22 22:11

Dan Vinton


1 Answers

@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 (@Beans in non-@Configuration classes, etc).

like image 81
axtavt Avatar answered Nov 14 '22 22:11

axtavt