项目中需要继承Quartz框架。项目的环境是SSM框架
遇到的问题是:在quartz的Job中使用@Autowired自动注入service时候报错,报service为null。
quarz调度不受spring容器管理,不能直接使用@AutoWired注入service
问题:如何在非spring容器中(非controller中)使用service方法。
思路:可以通过ApplicationContext 实例去获取bean
解决方法:
1、编写工具类继承ApplicationContextAware类
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.ComponentScan;
public class ApplicationContextSup implements ApplicationContextAware{
private static ApplicationContext context ;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
context=applicationContext;
}
public static Object getBean(String beanName){
return context.getBean(beanName);
}
public static <T> T getBean(Class<T> tClass){
return context.getBean(tClass);
}
}
2、在spring.xml中配置bean如下:
<bean id="ApplicationContextSup" class="com.quarz.ApplicationContextSup"></bean>
3、在web.xml配置监听器
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
4、最后可以在quarz作业中使用ApplicationContext获取bean
AAService aaservice = (AAService) ApplicationContextSup.getBean(AAService.class);
在Quartz作业中,由于其不在Spring容器管理范围内,@Autowired无法正常注入Service。为了解决这个问题,可以创建一个工具类继承ApplicationContextAware,然后在spring.xml配置bean,并在web.xml中配置监听器。这样就可以在Quartz作业中通过ApplicationContext获取并使用Service实例。

1367

被折叠的 条评论
为什么被折叠?



