1.创建抽象接口BasicJob
public interface BasicJob {
public void doJob();
}
2.创建该接口的实现类FirstJob, SecondJob
@Component
public class FirstJob implements BasicJob{
@Override
public void doJob() {
System.out.println("this is the first job !");
}
}
@Component
public class SecondJob implements BasicJob {
@Override
public void doJob() {
System.out.println("this is the second job !");
}
}
3.创建一个job的管理工具JobExecutor
@Component
public class JobExecutor implements ApplicationContextAware, InitializingBean {
private ApplicationContext applicationContext;
private List<BasicJob> jobs;
// applicationContext 对象注入
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
// 可以简单理解 bean 的构造函数, 初始化bean的时候调用
@Override
public void afterPropertiesSet() throws Exception {
Map<String, BasicJob> beansOfType = applicationContext.getBeansOfType(BasicJob.class);
if (beansOfType != null && beansOfType.size() > 0) {
jobs = new ArrayList<BasicJob>(beansOfType.values());
}
}
// 编写一个简单的调用方法, 调用所有job一次
public void executeAllJob() {
if (jobs != null && jobs.size() > 0) {
for (BasicJob job : jobs) {
job.doJob();
}
}
}
}
4.在spring项目启动的时候进行jobExecutor调用
@SpringBootApplication
public class Application implements ApplicationRunner, ApplicationContextAware {
private ApplicationContext applicationContext;
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
@Override
public void run(ApplicationArguments args) throws Exception {
Map<String, JobExecutor> beansOfType = applicationContext.getBeansOfType(JobExecutor.class);
if (beansOfType != null && beansOfType.size() == 1) {
beansOfType.values().stream().forEach(x -> {
x.executeAllJob();
});
}
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
}