在java web项目中实现随项目启动的额外操作
前言
在web項(xiàng)目中經(jīng)常會(huì)遇到在項(xiàng)目啟動(dòng)初始,會(huì)要求做一些邏輯的實(shí)現(xiàn),比如實(shí)現(xiàn)一個(gè)消息推送服務(wù),實(shí)現(xiàn)不同類型數(shù)據(jù)同步的回調(diào)操作初始化,或則通知其他客戶服務(wù)器本項(xiàng)目即將啟動(dòng),等等。對(duì)于這種要求,目前個(gè)人了解到的方式只要有三種。
class ServletTest extends HttpServlet{@Overridepublic void init() throws ServletException {//do something; } }
2.? 添加web服務(wù)器的監(jiān)聽ServletContextListener來(lái)實(shí)現(xiàn),需要實(shí)現(xiàn)
class ServletListenerTest implements ServletContextListener{@Overridepublic void contextInitialized(ServletContextEvent servletContextEvent) {//do something when system start }@Overridepublic void contextDestroyed(ServletContextEvent servletContextEvent) {//do something while the system crash } } <listener><listener-class>com.guozg.test.service.ServletListenerTest</listener-class> </listener>?
3.? 通過(guò)Spring的監(jiān)聽事件,注冊(cè)一個(gè)Spring初始化容器時(shí)的監(jiān)聽,實(shí)現(xiàn)ApplicationListener<ContextRefreshedEvent>接口,并實(shí)現(xiàn)onApplicationEvent()方法。
/*** @auther guozg*/ @Service public class FolderUpdataLister implements ApplicationListener<ContextRefreshedEvent> {@Overridepublic void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {//do something}在spring的監(jiān)聽中,如果用到springmvc,由于父子容器的原因,會(huì)兩次調(diào)用初始化容器事件,使用時(shí)要注意考慮。但是優(yōu)點(diǎn)是此時(shí)可以使用spring的注入調(diào)用其他service。前面兩種與web服務(wù)器有關(guān)的,在實(shí)際運(yùn)用中可能會(huì)使用不成功,就是在web.xml中找不到目標(biāo)類,也即是web.xml的包中沒(méi)有引入目標(biāo)類的包。當(dāng)出現(xiàn)這種情況就可以選用第三種了。還有一種方式是在web服務(wù)器中再加一個(gè)Filter。好了,目前知道的就是這些,具體使用看情況而定。另外為了不占用web 服務(wù)器啟動(dòng)的資源和時(shí)間,可以考慮新起線程來(lái)做操作。
?
轉(zhuǎn)載于:https://www.cnblogs.com/guozhigang/p/9855009.html
總結(jié)
以上是生活随笔為你收集整理的在java web项目中实现随项目启动的额外操作的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: Luogu P3455 [POI2007
- 下一篇: BZOJ3508 开灯 [校内NOIP