Issue
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.
Solution
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
Answered By - smac89