最近在开发的时候,由于经常用到多线程,在线程中无法通过@Autowired方式注解注入ApplicationContext中的bean,因为线程类一般不会交给spring管理,必须要使用手工获取spring bean对象的方法才能较好得实现相应的功能。
那怎么实现手动获取springApplicationContext中的bean对象呢?
方法1:通过实现ServletContextListener接口
我们只需要写一个监听类,实现ServletContextListener接口,然后重写里面的抽象方法即可,具体如下:

程序员导航
优网导航旗下整合全网优质开发资源,一站式IT编程学习与工具大全网站
public class SpringContextListener implements ServletContextListener { private static ApplicationContext springContext; /** * 销毁方法 */ @Override public void contextDestroyed(ServletContextEvent arg0) { // 可以不管 } /** * 初始化方法 */ @Override public void contextInitialized(ServletContextEvent arg0) { springContext = WebApplicationContextUtils.getWebApplicationContext(arg0.getServletContext()); } public static ApplicationContext getApplicationContext() { return springContext; } public static void setApplicationContext(ApplicationContext cxt) { springContext = cxt; } }
然后再其他类中只要使用如下方法获取即可:
XXService service= SpringContextListener.getApplicationContext().getBean(XXService.class);
方法2:通过实现ApplicationContextAware 接口
@Component
public class SpringContextUtils implements ApplicationContextAware {
/**
* 上下文对象实例
*/
private static ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
SpringContextUtils.applicationContext = applicationContext;
}
/**
* 获取applicationContext
*
* @return
*/
public static ApplicationContext getApplicationContext() {
return applicationContext;
}
/**
* 通过name获取 Bean.
*
* @param name
* @return
*/
public static Object getBean(String name) {
return getApplicationContext().getBean(name);
}
/**
* 通过class获取Bean.
*
* @param clazz
* @param
* @return
*/
public static T getBean(Class clazz) {
return getApplicationContext().getBean(clazz);
}
/**
* 通过name,以及Clazz返回指定的Bean
*
* @param name
* @param clazz
* @param
* @return
*/
public static T getBean(String name, Class clazz) {
return getApplicationContext().getBean(name, clazz);
}
}
注意:写完了工具类,还需要在applicationContext.xml中配置 一行,让Spring进行对象管理:
或者也可以直接用注解的方式,在类上注解@Component,在上列代码中我们就用的此方式。
方法3:手动创建ApplicationContext对象
这种方法一般适用于junit单元测试,也是学习spring的入门方法,可以了解下,web项目还是尽量使用上面的两种方法:

AI 工具导航
优网导航旗下AI工具导航,精选全球千款优质 AI 工具集
ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
有了ApplicationContext就都可以根据getBean方法获取对应的管理对象了。
手动获取spring bean对象其实也并不是很难,代码也是比较简单,你掌握了吗?
© 版权声明
文章版权归作者所有,未经允许请勿转载。
相关文章
暂无评论...



