My approach is for the bean one wishes to access to implement InitializingBean
or use @PostConstruct
, and containing a static reference to itself.
For example:
@Service
public class MyBean implements InitializingBean {
private static MyBean instance;
@Override
public void afterPropertiesSet() throws Exception {
instance = this;
}
public static MyBean get() {
return instance;
}
}
Usage in your static class would therefore just be:
MyBean myBean = MyBean.get();
This way, no XML configuration is required, you don't need to pass the bean in as a constructor argument, and the caller doesn't need to know or care that the bean is wired up using Spring (i.e., no need for messy ApplicationContext
variables).
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…