CommandLineRunner 接口
Spring Boot应用程序在启动后,会遍历CommandLineRunner接口的实例并运行它们的run方法。
可以利用@Order注解来规定所有CommandLineRunner实例的运行顺序。
具体的实现
/**
* 项目启动时需要加载的方法
*/
@Order(value = 1)
@Component
public class StartConfig1 implements CommandLineRunner {
@Autowired
private EquipmentService equipmentService;
//连接tcp
@Autowired
private TcpClientsManageService tcpClientsManageService;
/**
* Callback used to run the bean.
* @param args incoming main method arguments
* @throws Exception on error
*/
@Override
public void run(String... args) throws Exception {
List<Equipment> equipmentList = equipmentService.queryEquipmentList();
try {
for (Equipment equipment : equipmentList) {
Boolean aBoolean = tcpClientsManageService.connTcp(equipment);
equipment.setEState("已连接");
equipmentService.updateEquipment(equipment);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
/**
* 项目启动时需要加载的方法
*/
@Order(value = 2)
@Component
public class StartConfig2 implements CommandLineRunner {
/**
* Callback used to run the bean.
* @param args incoming main method arguments
* @throws Exception on error
*/
@Override
public void run(String... args) throws Exception {
//自己的业务逻辑
}
}
最后结果
你会发现在项目启动后会执行这2个方法,根据Order由小到大依次执行。
共有 0 条评论