转载文章:http://blog.youkuaiyun.com/u012907049/article/details/73801122
在上面文章的基础上我做了一些小改动。
1:原文章用的是application.yml,我这里用的application.properties.并且把mapper.xml文件放到了resoures下
application.properties配置
spring.datasource.url=jdbc:mysql://localhost:3306/quartz?useUnicode=true
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
mybatis.mapper-locations=classpath:mapper/*.xml
mybatis.mapper-locations.type-aliases-package=quartz.entity
mapper.xml目录结构如下
2:新增了工具类ApplicationContextUtil,目的是为了能在job类中注入spring对象,代码如下
@Service
public class ApplicationContextUtil implements ApplicationContextAware{
private static ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
ApplicationContextUtil.applicationContext=applicationContext;
}
public static Object getBean(Class beanName){
return applicationContext.getBean(beanName);
}
}
工具类实现了ApplicationContextAware接口,spring保证在ApplicationContextUtil实例化时去调用setApplicationContext方法,把上下文对象设置到静态变量applicationContext中。
需要注意两点:1:ApplicationContextUtil必须是spring管理的对象,这里加了注解@Service;2:applicationContext属性必须是静态的。
3:新增了TestService接口和TestServiceImpl实现类,为了测试注入功能,实现类代码如下
@Service
public class TestServiceImpl implements TestService{
public void test(){
System.out.println("TestServiceImpl run");
}
}
4:改造了HelloJob类,实现注入了一个TestService,代码如下
public class HelloJob implements BaseJob {
@Autowired
private ApplicationContextUtil applicationContextUtil;
TestService bean = (TestService) applicationContextUtil.getBean(TestService.class);
private static Logger _log = LoggerFactory.getLogger(HelloJob.class);
public void execute(JobExecutionContext context)
throws JobExecutionException {
bean.test();
_log.error("Hello Job执行时间: " + new Date());
}
}