背景
最近想用监听器定时更新表数据。实践中发现通过监听器实例化的对象,加上@Autowired的对象会为null。
简单记录两种方法备忘
第一种
在监听类的contextInitialized的方法中加上
WebApplicationContextUtils.getRequiredWebApplicationContext(sce.getServletContext())
.getAutowireCapableBeanFactory().autowireBean(this);
第二种
利用ApplicationContextAware接口获取容器中的实例
@Service
public class ApplicationContextHelper implements ApplicationContextAware
{
private static ApplicationContext applicationContext;
public void setApplicationContext(ApplicationContext _applicationContext)
throws BeansException
{
applicationContext = _applicationContext;
}
public static Object getBean(String beanName)
{
return applicationContext.getBean(beanName);
}
}
加载Spring配置文件时,如果Spring配置文件中所定义的Bean类实现了ApplicationContextAware 接口,那么在加载Spring配置文件时,会自动调用ApplicationContextAware 接口中的
public void setApplicationContext(ApplicationContext context) throws BeansException
获得ApplicationContext对象,ApplicationContext对象是由spring注入的。前提必须在Spring配置文件中指定该类
使用方法:
userService = (UserService) ApplicationContextHelper.getBean("userService");
通过这种方式获取容器中的实例对象,不需要通过@Autowired来实现