[英]Can I get all the beans in a method annotated with @PostConstruct?
As far as I know, A method annotated with @PostConstruct will be executed after its bean has been initialized.据我所知,用@PostConstruct 注释的方法将在其 bean 初始化后执行。
So can I get all the beans in this method?那么我可以用这个方法得到所有的豆子吗? Like this...
像这样...
@CustomAnnotation
public class Foo {
}
@Service
public class TestBean {
@Autowired
private Application context;
@PostContruct
public void init() {
// get all beans annotated with @CustomAnnotation
context.getBeansWithAnnotation(CustomAnnotation.class);
// to do something...
}
}
If the TestBean is initialized before the Foo, does the Foo can be detected in init()?如果 TestBean 在 Foo 之前初始化,在 init() 中是否可以检测到 Foo?
Spring initialization has at least two distinct steps when it comes to singleton beans.对于单例 bean,Spring 初始化至少有两个不同的步骤。
Before the actual singleton bean instances are created, and your @PostConstruct
method is called, the bean factory reads al the available configurations (eg XML files, Groovy scripts, @Configuration
classes, other) and registers all the encountered bean definitions.在创建实际的单例 bean 实例和调用
@PostConstruct
方法之前,bean 工厂读取所有可用配置(例如 XML 文件、Groovy 脚本、 @Configuration
Configuration 类等)并注册所有遇到的 bean 定义。
getBeansWithAnnotation()
should find a Foo
bean, if it wasn't created from it's bean definition before it will be created when you request it in @PostConstrust
. getBeansWithAnnotation()
应该找到一个Foo
bean,如果它不是从它的 bean 定义中创建的,那么当您在@PostConstrust
请求它时它将被创建。 You can try to force this scenario with @DependsOn
however it may lead to circular dependency problem:您可以尝试使用
@DependsOn
强制这种情况,但它可能会导致循环依赖问题:
@Component
@DependsOn("testBean")
@CustomAnnotation
public class Foo {
}
@Service("testBean")
public class TestBean {
@Autoware
private Application context;
@PostContruct
public void init() {
context.getBeansWithAnnotation(CustomAnnotation.class);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.