非spring托管对象如何获取到spring托管对象

一些thread类或servlet不能通过spring注解的方式调用spring容器里面的类尝试将thread或servlet加上@component或@controller注解变成被spring容器管理,再调用spring容器里面的其他类,失败!最终找出下面两种解决方案:一,通过spring配置文件applicationContext.xml初始化[java] view plaincopyimport org.springframework.context.ApplicationContext; import org.springframework.context.support.FileSystemXmlApplicationContext; public class SpringUtil{ private static ApplicationContext applicationContext = null; public static ApplicationContext getApplicationContext() { if(applicationContext == null){ applicationContext = new FileSystemXmlApplicationContext("applicationContext.xml"); } return applicationContext; } } 缺点:这里面的applicationContext.xml是全文件路径,这也是这种方式不是很灵活的原因之一,调用SpringUtil会创建一次ApplicationContext对象.如果将static去掉改为非静态,那么每次调用该方法时都会new一个该对象,效率应该会更差.二,通过实现ApplicationContextAware接口在spring初始化时,会通过该接口实现的setApplicationComtext方法将ApplicationContext对象注入到该类中,具体见下面我的解决方式选择该种:

1、定义SpringUtil

import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; public class SpringUtil implements ApplicationContextAware { private static ApplicationContext applicationContext; public static ApplicationContext getApplicationContext() { return applicationContext; } public void setApplicationContext(ApplicationContext applicationContext)throws BeansException { SpringUtil.applicationContext = applicationContext; }

}

2、spring的配置文件加入

<bean id="applicationContext" class="com.lefu.pushCore.other.SpringUtil"/>

3、通过如下方法便能获取到所有由spring管理的对象了:

PushController pushController = (PushController) SpringUtil.getApplicationContext().getBean("pushController");参考文章:

,我们人生中最大的懒惰,就是当我们明知自己拥有作出选择的能力,

非spring托管对象如何获取到spring托管对象

相关文章:

你感兴趣的文章:

标签云: