1、问题原因
被static修饰变量,是不属于任何实例化的对象拥有,spring的依赖注入只能在对象层级上进行依赖注入,所以不能直接使用@autowired标签进行注入。
2.解决方案
①在静态方法中使自定义的工具类,该工具类实现ApplicationContextAware ,在该工具类中通过applicationContext.getBean 来获取想要的bean类。
public class SpringContextUtil implements ApplicationContextAware {
private static ApplicationContext applicationContext = null;
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
SpringContextUtil.applicationContext = applicationContext;
}
public static ApplicationContext getApplicationContext() {
return applicationContext;
}
public static Object getBean(String beanName) {
return applicationContext.getBean(beanName);
}
public static Object getBeanByNull(String beanName) {
try {
return applicationContext.getBean(beanName);
}
catch (NullPointerException e)
{
return null;
}
}
public static boolean containsBean(String beanName) {
return applicationContext.containsBean(beanName);
}
}
②使用@autowired 标签进行set方法注入。具体为,将需要注入的bean申明为静态的全局变量, 在通过set方法注入,在静态方法中就能直接使用该变量。例如下面描述的 在静态方法中dosomething中想要使用bean类 MyTestBean.
@Component
public class Myclass{
private static MyTestBean mytestbean;
@Autowired
public void setMyTestBean(MyTestBean mytestbean){
Myclass.mytestbean=mytestbean;
}
public static void dosomething(){
mytestbean....;
}
}