0

Say for example, I have some beans annotated with @Foo, and I want to keep track of these because I want to control what happens when they are initialized, is there a way to register a custom spring beanfactory that will allow me to do this?

What if I had another annotation @Bar which also needs this special initialization?

My initial thought was to inform the user to annotated each bean with @Lazy annotation, then using a bean factory post processor, I will change some properties of the bean definition.

smac89
  • 39,374
  • 15
  • 132
  • 179
  • 1
    Are those annotations custom made by you, or spring annotations? If they were made by you, you probably already have control over their lifecycle. If not, you can use `beanFactoryPostProcessor` and `beanPostProcessor` to alter their initialization on different parts of their lifecycle. This question might help: https://stackoverflow.com/questions/30455536/beanfactorypostprocessor-and-beanpostprocessor-in-lifecycle-events – Gabriel Robaina Jul 18 '19 at 00:49

1 Answers1

0

The solution is to implement the BeanFactoryPostProcessor interface. This gives us access to the BeanDefinition before any of the beans are instantiated, therefore allowing us to change things like the scope, or make the bean lazy initialized or even change the constructor arguments of the bean!

If your spring application is manually started i.e. by creating a SpringApplicationBuilder, then you can even pass an instance of this class to the constructor of the builder and it will be used once the application is started.

@Component
public class FooBarBeanFactoryPostProcessor implements BeanFactoryPostProcessor {
    @Override
    public void postProcessBeanFactory(@NonNull ConfigurableListableBeanFactory beanFactory) throws BeansException {
        /*
        String[] fooBeans = beanFactory.getBeanNamesForAnnotation(Foo.class);
        BeanDefinition bean = beanFactory.getBeanDefinition(...);

        /* do your processing here ... */
    }
}

p.s. @Component annotation is required for this to work

smac89
  • 39,374
  • 15
  • 132
  • 179