springmvc系统启动自动执行任务


	<context:component-scan base-package="**.listener" />

在springmvc中配置扫描包

在该包下创建一个相关类

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

猜你喜欢

转载自blog.csdn.net/weixin_41402352/article/details/85643397
今日推荐