#RT,废话不多说直接进入主题:
在spring中通常采取注入的方式获取bean,比如
@Resource
private SystemConfig systemConfig;
@Autowired
private OssService coreConfig;
前提是使用这些注解的类也要纳入spring容器进行管理比如加上注解@Component。
但是,有时候需要在非spring管理的模块里使用bean,比如工具类Untils等。这种情况获取bean的方法有多种,在此只介绍其中之二,
一:借助ApplicationContextAware接口
编写一个实现ApplicationContextAware接口,这个接口只有一个方法
void setApplicationContext(ApplicationContext var1) throws BeansException;
代码示例:
@Component
public class SpringUtils implements ApplicationContextAware {
private static ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
SpringUtils.applicationContext = applicationContext;
}
public static ApplicationContext getApplicationContext(){
return applicationContext;
}
public static <T> T getBean(Class<T> clazz){
return applicationContext.getBean(clazz);
}
public static Object getBean(String name){
return applicationContext.getBean(name);
}
}
在spring容器加载的时候会执行setApplicationContext方法,拿到ApplicationContext(spring上下文),再通过applicationContext拿到bean,如:
SystemConfig bean = SpringUtils.getBean(SystemConfig.class)
二:借助spring的工具类WebApplicationContextUtils
代码示例如下:
//普通类中
ServletContext sc = ContextLoader.getCurrentWebApplicationContext().getServletContext();
//使用request
ServletContext sc = request.getServletContext();
//通过webApplicationContextUtils获取ApplicationContext
ApplicationContext ac = WebApplicationContextUtils.getWebApplicationContext(sc);
SystemConfig bean = ac.getBean(SystemConfig.class);
这种方法其实也是通过获取spring上下文ApplicationContext来拿到bean的。