项目场景:
项目是ssm环境的
问题描述:
使用quartz的job类写自己业务代码需要用到一个实体的sevrvice,无论用注解还是xml配置,service都是null
原因分析:
可能是定时器里面的作业类job的一些加载优先级过高,所以它加载进容器时,service还没加载,导致在job类使用service时还是null。
解决方案:
就是自己写一个获取容器applicationContext的工具类,然后根据service类名去获取自己需要的service
自己找个包底下新建这么一个类
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
@Component
public class GetBeanUtils implements ApplicationContextAware {
private static ApplicationContext context;
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
context = applicationContext;
}
public static ApplicationContext getApplicationContext() {
return context;
}
/**
* 这个获取不了
* @param name
* @return
*/
public static Object getBeans(String name) {
ApplicationContext applicationContext = getApplicationContext();
Object object = applicationContext.getBean(name);
return object;
}
/**
* 用这个获取
* @param tClass
* @return
*/
public static <T> T getBean(Class<T> tClass){
return context.getBean(tClass);
}
}
然后在你的job类用这个类的getBean方法就能获取了
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.gary.service.StudentService;
@Component
public class RestoreStudentJob implements Job {
@Autowired
private StudentService studentService;
public void execute(JobExecutionContext context) {
studentService = (StudentService)GetBeanUtils.getBean(StudentService.class);
System.out.println("===========================");
studentService.getStudent(10001);
}