解決Spring+Quartz不能註入Bean的問題
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");
解決Spring+Quartz不能註入Bean的問題