[英]How to run a method after one bean but before another bean in Spring?
How to run a method which depends on some bean before another bean? 如何在另一个bean之前运行一个依赖于某个bean的方法?
I have two beans. 我有两个豆子。 SecondBean
depends on FirstBean
. SecondBean
依赖于FirstBean
。 Also, before SecondBean
is created I have to perform some initialization logic which should be performed with FirstBean
and some other beans. 此外,在创建SecondBean
之前,我必须执行一些初始化逻辑,该逻辑应该使用FirstBean
和其他一些bean来执行。
I would imagine something like this (it doesn't work because initialization is not a Bean): 我会想象这样的事情(它不起作用因为初始化不是Bean):
@Autowired
public void initialization(FirstBean firstBean, SomeTotalyOtherBean otherBean){
firstBean.doSomething(otherBean);
}
@Bean
@DependsOn("initialization")
public SecondBean secondBean(FirstBean firstBean) {
return new SecondBean(firstBean);
}
@Bean
public FirstBean firstBean() {
return new FirstBean();
}
I know that I could just move all initialization process into firstBean
method but in my case it doesn't seem right because this process isn't connected with firstBean
creation. 我知道我可以将所有初始化过程移动到firstBean
方法中,但在我的情况下,它似乎并不正确,因为此过程与firstBean
创建无关。 I could also move the initialization process into secondBean
method but it also doesn't fit there because this logic isn't connected with secondBean
creation. 我也可以将初始化过程移动到secondBean
方法,但它也不适合那里,因为这个逻辑与secondBean
创建没有关联。 It is just a logic which in only this scenario has to be performed between those beans creation. 它只是一种逻辑,只有在这种情况下才能在这些bean创建之间执行。
Merge firstBean() and initialization(...) such that firstBean() returns the initialized bean. 合并firstBean()和初始化(...),以便firstBean()返回初始化的bean。
Imo it's a better design to only publish a component once it is ready to be used as a dependency / initialized. Imo是一个更好的设计,只有在准备好用作依赖/初始化后才能发布它。
Edit: could the initialization happen in FirstBean's constructor? 编辑:初始化可能发生在FirstBean的构造函数中吗?
It sounds as easy as/one possible approach: 听起来像一种可能的方法一样简单:
/*@Autowired
public void initialization(FirstBean firstBean, SomeTotalyOtherBean otherBean){
firstBean.doSomething(otherBean);
}*/
@Bean
@Autowired //!
//@DependsOn("initialization")
public SecondBean secondBean(FirstBean firstBean) {
return new SecondBean(firstBean);
}
@Autowired //! SomeTotalyOtherBean should be "visible" to this context...
@Bean
public FirstBean firstBean(SomeTotalyOtherBean other) {
FirstBean chill = new FirstBean();//
chill.doSomething(other);
return chill;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.