在开发中可能会有这样的情景。需要在容器启动的时候执行一些内容。比如读取配置文件,数据库连接之类的。SpringBoot给我们提供了两个接口来帮助我们实现这种需求。这两个接口分别为CommandLineRunner和ApplicationRunner。他们的执行时机为容器启动完成的时候。
这两个接口中有一个run方法,我们只需要实现这个方法即可。这两个接口的不同之处在于:ApplicationRunner中run方法的参数为ApplicationArguments,而CommandLineRunner接口中run方法的参数为String数组。目前我在项目中用的是ApplicationRunner。是这么实现的:
package com.coship.da.thread;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.apache.log4j.Logger;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;
@Component
public class ThreadListener implements ApplicationRunner {
private static final Logger logger = Logger.getLogger(ReportInfoThread.class);
@Override
public void run(ApplicationArguments args) throws Exception {
// TODO Auto-generated method stub
logger.info("处理线程池开始创建");
int threadPoolSize = 10;
ExecutorService fixedThreadPool = Executors.newFixedThreadPool(threadPoolSize);
for (int i = 0; i < threadPoolSize; i++) {
fixedThreadPool.execute(new Thread(new ReportInfoThread(),String.valueOf(i)));
}
logger.info("处理线程池创建结束");
}
}