让Spring处理所有bean的生命周期是很常见的,否则可能会有些棘手。不是spring bean的对象有望在某个地方初始化。使该初始化程序成为spring bean,并使它了解应用程序上下文
public class SpringContextHolder implements ApplicationContextAware {private static ApplicationContext applicationContext = null;
public static ApplicationContext getApplicationContext() { return applicationContext;}public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.applicationContext = applicationContext;}public void init(){ ServiceBean1 srv1 = (ServiceBean1)applicationContext.getBean("serviceBean1"); myNonSpringObject.setService1(srv1); // Or something}}
设置独立的spring应用非常容易。只需创建一个Spring XML并连接您的bean(通过扫描/注释或XML)即可。确实不建议在main方法中执行此操作,但是您可以轻松地弄清楚如何在独立应用程序中进行此设置。请记住,您的应用程序本身不应真正执行太多的生命周期逻辑,而应让Spring来执行。
public class StandaloneSpringApp{public static void main(String[] args){
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(“applicationContext.xml”);SomeBeanType bean = (SomeBeanType)ctx.getBean("SomeBeanName");bean.doProcessing(); // or whatever}
}
您的设置非常合理,即使我无法看到您的整个范围,您的方法也是大型模块化弹簧应用的良好起点。



