samshers
samshers

Reputation: 3690

How to get list of beans defined in a java config class?

A spring java configuration class can have more than one bean defined in it. I am aware on how to obtain a single bean which is defined in a java spring configuration class. Some thing like -

AnnotationConfigApplicationContext ctx = new  AnnotationConfigApplicationContext(BeanConfigurer.class);
ClassA a = ctx.getBean(ClassA.class);

But I want to know if using a single method call is there a way to obtain every bean defined in the configuration class. The bean configurer class is something like below. All classes - ClassA, ClassB, ClassC extend a common parent ClassAlphabet.

@Configuration
public class BeanConfigurer {

    @Bean
    public ClassA classA()
    {
        return new ClassA () ;
    }


    @Bean
    public ClassB classB()
    {
        return new ClassB () ;
    }


    @Bean
    public ClassC classC()
    {
        return new ClassC () ;
    }

}

And I am interested in doing a single method call and get all the beans in to a list. something like below:

 List<ClassAlphabet> listOfClasses = ctx.getBeans(ClassAlphabets.class); 

or simply

List<ClassAlphabet> listOfClasses = ctx.getBeans();

Is it possible??

Upvotes: 3

Views: 1183

Answers (1)

glytching
glytching

Reputation: 48015

You can use ctx.getBeansOfType(ClassAlphabets.class).

<T> Map<String, T> getBeansOfType(Class<T> type) throws BeansException;

More details in the Javadocs.

This does not necessarily do this: "get list of beans defined in a java config class" but it does meet the requirement implied by this quasi code from the OP:

List<ClassAlphabet> listOfClasses = ctx.getBeans(ClassAlphabets.class); 
List<ClassAlphabet> listOfClasses = ctx.getBeans();

Upvotes: 2

Related Questions