How to run a method which depends on some bean before another bean?
I have two beans. SecondBean
depends on FirstBean
. Also, before SecondBean
is created I have to perform some initialization logic which should be performed with FirstBean
and some other beans.
I would imagine something like this (it doesn't work because initialization is not a 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. 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. It is just a logic which in only this scenario has to be performed between those beans creation.
Merge firstBean() and initialization(...) such that firstBean() returns the initialized bean.
Imo it's a better design to only publish a component once it is ready to be used as a dependency / initialized.
Edit: could the initialization happen in FirstBean's constructor?
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;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.