Spring Task如何注入Service??????

Spring Task如何注入Service??????Spring Task如何注入Service??????Spring Task如何注入Service??????Spring Task如何注入Service??????

由于定时器的执行优先于注入,因此我们不能通过@Resource注入service,我们需要创建一个类ApplicationContextUtil,用来获取service。原来Spring定时器可以这样注入service
图片说明

定时器中通过ApplicationContextUtil类,获得service。
图片说明
注:相对应的,在service中需要配置service名称。
图片说明

创建一个来获取service

1、引入ApplicationContextUtil的工具类
2、在execute方法中以这种方式进行对service进行注入

spring4 亲测可以使用
图片说明

图片说明

前期项目中用Task执行定时任务,相关方法简单分享下:
1、Task随Spring启动,配置在Spring-mvc.xml中:
<?xml version="1.0" encoding="UTF-8"?>
xmlns:task="http://www.springframework.org/schema/task"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xmlns:jms="http://www.springframework.org/schema/jms"
xsi:schemaLocation="
http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.0.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/jms http://www.springframework.org/schema/jms/spring-jms-4.0.xsd"
default-lazy-init="true">

<description>task</description>

<!-- 定时任务-->
<task:scheduler id="dataJob" pool-size="1"/>  
<task:scheduled-tasks scheduler="dataSync">   
        <task:scheduled ref="dataSyncService" method="syn" fixed-delay="60000"/>   
</task:scheduled-tasks>


2、Service定义:
@Service
public class DataSyncService extends BaseService {

// 任务方法
@Transactional
public void syn() {
}
}

楼主问的是不是动态管理的JOB,静态添加的job,不管是spring配置文件还是注解配置的job都是可以自动装配service的

图片说明

定时任务实现类

@Component
@Lazy(false)
public class Task {

@Resource
private TaskService taskService;

protected final Logger logger = LoggerFactory.getLogger(this.getClass());

/**
 * 每天1点执行
 */
@Scheduled(cron = "0 0 1 * * ?")
public void taskExecute() {
    try{
        taskService.executedTask();
        logger.info("task executed");
    }catch(Exception e){
        logger.error("",e);
    }
}

}

Spring配置


task类:

@Component
@Lazy(false)
public class Task {
@Resource
private TaskService taskService;
protected final Logger logger = LoggerFactory.getLogger(this.getClass());
/**
 * 每天1点执行
 */
@Scheduled(cron = "0 0 1 * * ?")
public void taskExecute() {
            try{
                    taskService.executedTask();
                    logger.info("task executed");
            }catch(Exception e){
                    logger.error("",e);
            }
    }
}

##spring配置:

 <!-- 定时器开关-->
       <task:annotation-driven scheduler="qbScheduler" mode="proxy"/>
       <task:scheduler id="qbScheduler" pool-size="10"/>