1. 程式人生 > >SpringMVC中定時器繼承Task後無法對service注入問題

SpringMVC中定時器繼承Task後無法對service注入問題

edisTask是通過定時器來每分鐘像資料庫裡推送的,於是就有了

public class RedisTask  extends Task {

    public void execute(TaskExecutionContext executor) throws RuntimeException {
        Scheduler scheduler = executor.getScheduler();
        TaskExecutor[] executors = scheduler.getExecutingTasks();
        if(executors!=null
&& executors.length>1)//排程未執行完時不啟用新任務

然後在定時器的任務中通過對Redis的呼叫,推送到本地資料庫

OrderService orderService = new OrderService();
Order order = new Order();
int num = orderService.add(order);
System.out.println("插入條數為:" + num);

那麼問題來了,tomcat開始沒次呼叫定時器的RedisTask就開始報錯,debug發現orderService為null,也就是說service根本就沒有注入。

然後我就在Spring的配置檔案裡檢視標註問題,發現根本沒問題,再然後發現此方法繼承了Task,於是乎恍然大悟

:定時器繼承了Task之後,在定時器呼叫此方法後會直接執行execute方法,來不急執行標註進行注入。

  @Resource
    private OrderService orderService;

然後解決方案:

1、引入ApplicationContextUtil的工具類

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 package com.aneop.common.util;
import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; public class ApplicationContextUtil implements ApplicationContextAware { private static ApplicationContext applicationContext; public static ApplicationContext getApplicationContext() { return applicationContext; } public void setApplicationContext(ApplicationContext applicationContext) { ApplicationContextUtil.applicationContext = applicationContext; } public static Object getBean(String beanName) { return applicationContext.getBean(beanName); } }

 2、在execute方法中以這種方式進行對service進行注入

OrderService orderService = (OrderService)ApplicationContextUtil.getBean("orderService");

注:在service的介面的@Service標註中必須寫明注入的名字。

@Service("orderService")
public class OrderServiceImpl implements OrderService {