spring容器启动事件和关闭事件

启动事件

实现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,springMVC)