[英]Custom initializing of beans annotated with a custom annotation
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? 比如说,我有一些用
@Foo
注释的@Foo
,我想跟踪它们,因为我想控制它们初始化时发生的事情,有没有办法注册自定义的spring beanfactory,这将允许我执行此操作?
What if I had another annotation @Bar
which also needs this special initialization? 如果我还有另一个注释
@Bar
也需要这种特殊的初始化怎么办?
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. 我最初的想法是通知用户使用
@Lazy
注释对每个bean进行注释,然后使用bean工厂的后处理器,我将更改bean定义的某些属性。
The solution is to implement the BeanFactoryPostProcessor
interface. 解决方案是实现
BeanFactoryPostProcessor
接口。 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! 这使我们可以在实例化任何Bean 之前访问
BeanDefinition
,因此允许我们更改诸如范围之类的内容,或者使Bean延迟初始化,甚至更改Bean的构造函数参数!
If your spring application is manually started ie 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. 如果您的spring应用程序是手动启动的,即通过创建
SpringApplicationBuilder
,那么您甚至可以将此类的实例传递给构建器的构造函数,并且在应用程序启动后将使用该实例。
@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 ... */
}
}
ps @Component
annotation is required for this to work 必须使用ps
@Component
批注
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.