1. 程式人生 > >spring容器啟動事件和關閉事件

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(); } } }