1

In an Spring Application it is possible to retrieve all (?) Beans with applicationContext.getBeansOfType(Object.class). This is of course only possible, after all Beans have been created.

So, if I call this method in the constructor of a Bean, I have to be lucky, to be the last Bean to be created, to have access to all of them.

As far as I understand the life cycle of Spring Beans, there is a phase in which BeanDefinitions are created, before the Beans are initialized.

  • How is it possible to retrive all created BeanDefinitions in the constructor of a Bean?
  • Can I also retrive the types (as Class) of those BeanDefinitions? The type BeanDefinition seems to only provide the "current bean class name of this bean definition".

Or is the only way to get those types after all Beans have been constructed (e.g. @PostConstruct)?

2 Answers2

1

You can create a last bean by putting it for example in an @Configuration class with a minimum initialization order, so that it is the last one with @Order(Ordered.LOWEST_PRECEDENCE), that would be it:

@Configuration
@Order(Ordered.LOWEST_PRECEDENCE)
public class Last {

    @Autowired
    ApplicationContext applicationContext;

    @Bean
    public String lastBean() {

        applicationContext.getBeanDefinitionNames();    //retrive all created BeanDefinitions in the constructor of a Bean

        applicationContext.getBeansOfType(Object.class); //retrive the types (as Class) 

        return "lastBean";
    }

}
Francesc Recio
  • 2,187
  • 2
  • 13
  • 26
1

Maybe this code could help

    for (String name : applicationContext.getBeanFactory().getBeanDefinitionNames()) {
        BeanDefinition beanDefinition = applicationContext.getBeanFactory().getBeanDefinition(name);
        String className = beanDefinition.getBeanClassName();
        Class<?> clazz = Class.forName(className);
    }

The loop gets you all the BeanDefinitions and then you load the class for each and do what you want?

By the way this might not be a good way to use Spring but it will work.

James Mudd
  • 1,816
  • 1
  • 20
  • 25
  • Hi James, this seems to be, what I've been looking for. Can you tell me, why this might not be a good way to use Spring? What I attempt to do is, configuring a Bean by processing Annotations on all Spring Beans (i.e. on all ComponentScans). Of course it would be possible to initialize the Bean after the construction, but then I am afraid, someone might try to use the Bean before it is fully initialized. – derM - not here for BOT dreams May 28 '19 at 15:03
  • Ok your use case sounds legitimate. I don't know of another way to achieve that. In general I would say that looking at the bean definitions might mean your trying to workaround Spring behaviour, but if that's what you need then its fine. This API is there to use. Glad it helped. – James Mudd May 28 '19 at 15:33