1.问题描述
在做一个老的springmvc项目时,需要封装一个模块config类专门读取配置文件,再将这个config类注入到具体场景中。
ApplicationConfig是一个读取配置文件的类,在service层中可以使用@AutoWired实现自动注入,但是在普通类中无法自动注入,报空指针异常
2.原因分析
因为一般普通的Java类没有被spring代理,无法通过spring注入相关的对象
3.解决办法
1)写一个工具类获取spring应用上下文,通过getBean方式获取
public class SpringContextUtil implements ApplicationContextAware {
private static ApplicationContext applicationContext; // Spring应用上下文
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
SpringContextUtil.applicationContext = applicationContext;
}
public static ApplicationContext getApplicationContext() {
return applicationContext;
}
public static Object getBean(String name) throws BeansException {
return applicationContext.getBean(name);
}
public static Class getType(String name)
throws NoSuchBeanDefinitionException {
return applicationContext.getType(name);
}
}
2)在spring配置文件中配置这个类
<bean id="SpringContextUtil" class="com.cpsoft.common.utils.SpringContextUtil"
scope="singleton"></bean>
3)在普通类中使用