基于注解和基于配置其实用法差不多
package cn.test.task;
import javax.annotation.Resource;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import cn.test.service.DataService;
@Component
public class PhotoPost {
@Resource
private DataService dataService;
@Scheduled(cron = "0/10 * * * * ? ")
public void run() {
System.out.println("定时任务进行中.......");
dataService.test();
}
}
但这里有一个值得注意的地方,之前将配置写入spring配置文件的同学会发现一个很费解的问题,如果上面代码中的bean自动注入会碰到NullPointException。这是怎么回事呢,定时任务会优先于注解加载。
所以我们这里换了中方法配置,将Task的配置内容放在了spring-mvc的配置文件中(也可以是其它加载优先级不那么高的配置项里),这样就顺利执行了