Spring-MVC的應用中,要實現應用啟動時就執行特定處理的功能,主要是通過實現下面這些接口(任選一,至少一個即可)
一、ApplicationContextAware接口
1 package org.springframework.context;
2
3 import org.springframework.beans.BeansException;
4 import org.springframework.beans.factory.Aware;
5 import org.springframework.context.ApplicationContext;
6
7 public interface ApplicationContextAware extends Aware {
8 void setApplicationContext(ApplicationContext var1) throws BeansException;
9 }
二、ServletContextAware 接口
1 package org.springframework.web.context;
2
3 import javax.servlet.ServletContext;
4 import org.springframework.beans.factory.Aware;
5
6 public interface ServletContextAware extends Aware {
7 void setServletContext(ServletContext var1);
8 }
三、InitializingBean 接口
1 package org.springframework.beans.factory;
2
3 public interface InitializingBean {
4 void afterPropertiesSet() throws Exception;
5 }
四、ApplicationListener<ApplicationEvent> 接口
1 package org.springframework.context;
2
3 import java.util.EventListener;
4 import org.springframework.context.ApplicationEvent;
5
6 public interface ApplicationListener<E extends ApplicationEvent> extends EventListener {
7 void onApplicationEvent(E var1);
8 }
示例程序:
1 package test.web.listener;
2
3 import org.apache.logging.log4j.*;
4 import org.springframework.beans.*;
5 import org.springframework.beans.factory.InitializingBean;
6 import org.springframework.context.*;
7 import org.springframework.context.event.ContextRefreshedEvent;
8 import org.springframework.stereotype.Component;
9 import org.springframework.web.context.ServletContextAware;
10 import javax.servlet.ServletContext;
11
12 @Component
13 public class StartupListener implements ApplicationContextAware, ServletContextAware,
14 InitializingBean, ApplicationListener<ContextRefreshedEvent> {
15
16 protected Logger logger = LogManager.getLogger();
17
18 @Override
19 public void setApplicationContext(ApplicationContext ctx) throws BeansException {
20 logger.info("1 => StartupListener.setApplicationContext");
21 }
22
23 @Override
24 public void setServletContext(ServletContext context) {
25 logger.info("2 => StartupListener.setServletContext");
26 }
27
28 @Override
29 public void afterPropertiesSet() throws Exception {
30 logger.info("3 => StartupListener.afterPropertiesSet");
31 }
32
33 @Override
34 public void onApplicationEvent(ContextRefreshedEvent evt) {
35 logger.info("4.1 => MyApplicationListener.onApplicationEvent");
36 if (evt.getApplicationContext().getParent() == null) {
37 logger.info("4.2 => MyApplicationListener.onApplicationEvent");
38 }
39 }
40
41 }
運行時,輸出的順序如下:
1 => StartupListener.setApplicationContext
2 => StartupListener.setServletContext
3 => StartupListener.afterPropertiesSet
4.1 => MyApplicationListener.onApplicationEvent
4.2 => MyApplicationListener.onApplicationEvent
4.1 => MyApplicationListener.onApplicationEvent
注意:onApplicationEvent方法會觸發多次,初始化這種事情,越早越好,建議在setApplicationContext方法中處理。
文章摘自https://www.cnblogs.com/wihainan/p/6239263.html

