Spring application-quartz的配置
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util-4.0.xsd">
<bean id="ordersQuartz" class="org.springframework.scheduling.quartz.JobDetailFactoryBean">
<property name="name" value="exampleJob" />
<property name="jobClass" value="com.ak.orders.quartz.OrdersQuartz" />
</bean>
<bean id="taskTrigger" class="org.springframework.scheduling.quartz.CronTriggerFactoryBean">
<property name="jobDetail" ref="ordersQuartz" />
<property name="cronExpression" value="0 */8 * * * ?" />
</bean>
<bean id="schedulerFactoryBean"
class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
<property name="triggers">
<list>
<ref bean="taskTrigger" />
</list>
</property>
</bean>
</beans>
任务类
import org.springframework.scheduling.quartz.QuartzJobBean;
public class OrdersQuartz extends QuartzJobBean{
@Resource
private OrderService orderService ;
@Override
protected void executeInternal(JobExecutionContext arg0) throws JobExecutionException {
//任务内容
orderservice.saveOrders(orders);
}
}
问题
NullpointException
orderService 为 null . 调用不到方法.
解决:
1. 添加一个 系统帮助类
package com.ak.orders.quartz;
import java.util.Locale;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
/**
* 系统bean帮助类
*/
public class SpringContextUtil implements ApplicationContextAware {
private static ApplicationContext context;
@Override
@SuppressWarnings("static-access" )
public void setApplicationContext(ApplicationContext contex)
throws BeansException {
// TODO Auto-generated method stub
this.context = contex;
}
public static Object getBean(String beanName){
return context.getBean(beanName);
}
public static String getMessage(String key){
return context.getMessage(key, null, Locale.getDefault());
}
}
2. 在spring配置文件中添加一个 bean
<bean id="SpringContextUtil" class="com.ak.orders.quartz.SpringContextUtil"></bean>
3. 程序获取 bean 代码
private OrderService orderService = (OrderService)SpringContextUtil.getBean("parms");