1. 程式人生 > >如何讓springmvc在啟動的時候執行特定的業務處理

如何讓springmvc在啟動的時候執行特定的業務處理

context 文件 實現邏輯 .get config efi ren edev 4.2

如何讓springmvc在啟動的時候執行特定的業務處理

java 的 web服務器啟動時,經常會做一些特定的業務邏輯處理,比如數據庫初始化,

初始化系統參數,讀取配置文庫等。

很多web服務的中間件,可以 通過這樣的思路去實現。比如消息分發服務。

實現方法:

一、Web項目,非Spring

解決方法:實現【 ServletContextListener】 接口

(1)、把實現了ServletContextListener 的類配置到【 web.xml】 文件中

[html] view plain copy print?
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <web-app version="2.5"
  3. xmlns="http://java.sun.com/xml/ns/javaee"
  4. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  5. xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
  6. http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
  7. <display-name></display-name>
  8. <welcome-file-list>
  9. <welcome-file>index.jsp</welcome-file>
  10. </welcome-file-list>
  11. <listener>
  12. <listener-class>com.chinaso.init.StartInit</listener-class>
  13. </listener>
  14. <filter>
  15. <filter-name>struts2</filter-name>
  16. <filter-class>
  17. org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
  18. </filter-class>
  19. </filter>
  20. <filter-mapping>
  21. <filter-name>struts2</filter-name>
  22. <url-pattern>/*</url-pattern>
  23. </filter-mapping>
  24. </web-app>
    <?xml version="1.0" encoding="UTF-8"?>  
    <web-app version="2.5"   
        xmlns="http://java.sun.com/xml/ns/javaee"   
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"   
        xsi:schemaLocation="http://java.sun.com/xml/ns/javaee   
        http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">  
      <display-name></display-name>   
      <welcome-file-list>  
        <welcome-file>index.jsp</welcome-file>  
      </welcome-file-list>  
      <listener>  
        <listener-class>com.chinaso.init.StartInit</listener-class>  
      </listener>  
      <filter>  
        <filter-name>struts2</filter-name>  
        <filter-class>  
            org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter  
        </filter-class>  
      </filter>  
      <filter-mapping>  
        <filter-name>struts2</filter-name>  
        <url-pattern>/*</url-pattern>  
      </filter-mapping>  
      </web-app>  

(2)、加入自己的實現邏輯

[java] view plain copy print?
  1. public class StartInit implements ServletContextListener {
  2. static final Logger logger = LoggerFactory.getLogger(StartInit.class);
  3. // 系統初始化執行方法
  4. public void contextDestroyed(ServletContextEvent e) {
  5. logger.info("系統停止...");
  6. }
  7. public void contextInitialized(ServletContextEvent e) {
  8. logger.info("系統初始化開始...");
  9. // 獲取項目根目錄
  10. String root_path = e.getServletContext().getRealPath("/");
  11. logger.info("application path : {}",root_path);
  12. // 初始化 ConfigFactorty
  13. ConfigFactory.init(root_path);
  14. // 初始化數據鏈接信息
  15. DBManager.init();
  16. // 初始化定時統計任務
  17. TaskManager.init();
  18. // 初始化用戶信息查詢位置
  19. UserInfo.init();
  20. logger.info("系統初始化結束...");
  21. }
  22. }
    public class StartInit implements ServletContextListener {  
        static final Logger logger = LoggerFactory.getLogger(StartInit.class);  
        // 系統初始化執行方法  
        public void contextDestroyed(ServletContextEvent e) {  
            logger.info("系統停止...");  
        }  
      
        public void contextInitialized(ServletContextEvent e) {  
            logger.info("系統初始化開始...");  
              
            // 獲取項目根目錄  
            String root_path  = e.getServletContext().getRealPath("/");  
            logger.info("application path : {}",root_path);  
              
            // 初始化 ConfigFactorty  
            ConfigFactory.init(root_path);  
            // 初始化數據鏈接信息  
            DBManager.init();  
            // 初始化定時統計任務  
            TaskManager.init();  
            // 初始化用戶信息查詢位置  
            UserInfo.init();  
              
            logger.info("系統初始化結束...");  
        }  
          
    }  

二、Spring項目

Spring-MVC的應用中,要實現類似的功能,主要是通過實現下面這些接口(任選一,至少一個即可)

1、ApplicationContextAware接口

[java] view plain copy print?
  1. package org.springframework.context;
  2. import org.springframework.beans.BeansException;
  3. import org.springframework.beans.factory.Aware;
  4. import org.springframework.context.ApplicationContext;
  5. public interface ApplicationContextAware extends Aware {
  6. void setApplicationContext(ApplicationContext var1) throws BeansException;
  7. }
package org.springframework.context;
 
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.Aware;
import org.springframework.context.ApplicationContext;
 
public interface ApplicationContextAware extends Aware {
    void setApplicationContext(ApplicationContext var1) throws BeansException;
}


2、ServletContextAware 接口

[java] view plain copy print?
  1. package org.springframework.web.context;
  2. import javax.servlet.ServletContext;
  3. import org.springframework.beans.factory.Aware;
  4. public interface ServletContextAware extends Aware {
  5. void setServletContext(ServletContext var1);
  6. }
package org.springframework.web.context;
 
import javax.servlet.ServletContext;
import org.springframework.beans.factory.Aware;
 
public interface ServletContextAware extends Aware {
    void setServletContext(ServletContext var1);
}

3、InitializingBean 接口

[java] view plain copy print?
  1. package org.springframework.beans.factory;
  2. public interface InitializingBean {
  3. void afterPropertiesSet() throws Exception;
  4. }
package org.springframework.beans.factory;
 
public interface InitializingBean {
    void afterPropertiesSet() throws Exception;
}

4、ApplicationListener<ApplicationEvent> 接口

[java] view plain copy print?
  1. package org.springframework.context;
  2. import java.util.EventListener;
  3. import org.springframework.context.ApplicationEvent;
  4. public interface ApplicationListener<E extends ApplicationEvent> extends EventListener {
  5. void onApplicationEvent(E var1);
  6. }
package org.springframework.context;
 
import java.util.EventListener;
import org.springframework.context.ApplicationEvent;
 
public interface ApplicationListener<E extends ApplicationEvent> extends EventListener {
    void onApplicationEvent(E var1);
}

[java] view plain copy print?
  1. package test.web.listener;
  2. import org.apache.logging.log4j.*;
  3. import org.springframework.beans.*;
  4. import org.springframework.beans.factory.InitializingBean;
  5. import org.springframework.context.*;
  6. import org.springframework.context.event.ContextRefreshedEvent;
  7. import org.springframework.stereotype.Component;
  8. import org.springframework.web.context.ServletContextAware;
  9. import javax.servlet.ServletContext;
  10. @Component
  11. public class StartupListener implements ApplicationContextAware, ServletContextAware,
  12. InitializingBean, ApplicationListener<ContextRefreshedEvent> {
  13. protected Logger logger = LogManager.getLogger();
  14. @Override
  15. public void setApplicationContext(ApplicationContext ctx) throws BeansException {
  16. logger.info("1 => StartupListener.setApplicationContext");
  17. }
  18. @Override
  19. public void setServletContext(ServletContext context) {
  20. logger.info("2 => StartupListener.setServletContext");
  21. }
  22. @Override
  23. public void afterPropertiesSet() throws Exception {
  24. logger.info("3 => StartupListener.afterPropertiesSet");
  25. }
  26. @Override
  27. public void onApplicationEvent(ContextRefreshedEvent evt) {
  28. logger.info("4.1 => MyApplicationListener.onApplicationEvent");
  29. if (evt.getApplicationContext().getParent() == null) {
  30. logger.info("4.2 => MyApplicationListener.onApplicationEvent");
  31. }
  32. }
  33. }
package test.web.listener;
 
import org.apache.logging.log4j.*;
import org.springframework.beans.*;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.*;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;
import org.springframework.web.context.ServletContextAware;
import javax.servlet.ServletContext;
 
@Component
public class StartupListener implements ApplicationContextAware, ServletContextAware,
        InitializingBean, ApplicationListener<ContextRefreshedEvent> {
 
    protected Logger logger = LogManager.getLogger();
 
    @Override
    public void setApplicationContext(ApplicationContext ctx) throws BeansException {
        logger.info("1 => StartupListener.setApplicationContext");
    }
 
    @Override
    public void setServletContext(ServletContext context) {
        logger.info("2 => StartupListener.setServletContext");
    }
 
    @Override
    public void afterPropertiesSet() throws Exception {
        logger.info("3 => StartupListener.afterPropertiesSet");
    }
 
    @Override
    public void onApplicationEvent(ContextRefreshedEvent evt) {
        logger.info("4.1 => MyApplicationListener.onApplicationEvent");
        if (evt.getApplicationContext().getParent() == null) {
            logger.info("4.2 => MyApplicationListener.onApplicationEvent");
        }
    }
 
}

運行時,輸出的順序如下:

1 => StartupListener.setApplicationContext
2 => StartupListener.setServletContext
3 => StartupListener.afterPropertiesSet
4.1 => MyApplicationListener.onApplicationEvent
4.2 => MyApplicationListener.onApplicationEvent
4.1 => MyApplicationListener.onApplicationEvent

註意:onApplicationEvent方法會觸發多次,初始化這種事情,越早越好,建議在setApplicationContext方法中處理。

如何讓springmvc在啟動的時候執行特定的業務處理