启动事件
实现ApplicationListener ContextRefreshedEvent
@Service
public class StartAddDataListener implements ApplicationListener<ContextRefreshedEvent> {
private Logger logger= LoggerFactory.getLogger(StartAddDataListener.class);
@Autowired
TCPServer tcpServer;
@Override
public void onApplicationEvent(ContextRefreshedEvent event) {
if(event.getApplicationContext().getParent() == null){
logger.info("spring Start Success");
NettyStartService nettyStartService=new NettyStartService();
nettyStartService.setTcpServer(tcpServer);
new Thread(nettyStartService).start();
}
}
}
关闭事件
implements ApplicationListener
@Service
public class StopAddDataListener implements ApplicationListener<ContextClosedEvent> {
private Logger logger= LoggerFactory.getLogger(StartAddDataListener.class);
@Autowired
TCPServer tcpServer;
@Override
public void onApplicationEvent(ContextClosedEvent contextClosedEvent) {
if(contextClosedEvent.getApplicationContext().getParent() == null) {
NettyStopService nettyStopService = new NettyStopService();
nettyStopService.setTcpServer(tcpServer);
new Thread(nettyStopService).start();
}
}
}

本文介绍了一种在Spring应用中实现启动和关闭事件监听的方法。通过实现ApplicationListener接口并覆盖onApplicationEvent方法来响应ContextRefreshedEvent和ContextClosedEvent,从而在Spring容器启动成功后启动Netty服务,在容器关闭时停止服务。
1310

被折叠的 条评论
为什么被折叠?



