zoukankan      html  css  js  c++  java
  • 当spring 容器初始化完成后执行某个方法

      在做web项目开发中,尤其是企业级应用开发的时候,往往会在工程启动的时候做许多的前置检查。比如检查是否使用了我们组禁止使用的Mysql的group_concat函数,如果使用了项目就不能启动,并指出哪个文件的xml文件使用了这个函数。而在Spring的web项目中,我们可以介入Spring的启动过程。我们希望在Spring容器将所有的Bean都初始化完成之后,做一些操作,这个时候我们就可以实现一个接口:

      方法一:

    1 package com.leadsoft.test.executor.processor
    2 public class InstantiationTracingBeanPostProcessor 
    3 implements ApplicationListener<ContextRefreshedEvent> {
    4 @Override
    5 public void onApplicationEvent(ContextRefreshedEvent event) {
    6 //需要执行的逻辑代码,当spring容器初始化完成后就会执行该方法。
    7 }
    8 }

      同时在Spring的配置文件中,添加注入:

    1 <!-- 当Spring容器启动完成后执行下面的这个Bean -->
    2 <bean class="com.leadsoft.test.executor.processor.InstantiationTracingBeanPostProcessor"/>

      但是这个时候,会存在一个问题,在web 项目中(spring mvc),系统会存在两个容器,一个是root application context ,另一个就是我们自己的 projectName-servlet context(作为root application context的子容器)。这种情况下,就会造成onApplicationEvent方法被执行两次。为了避免上面提到的问题,我们可以只在root application context初始化完成后调用逻辑代码,其他的容器的初始化完成,则不做任何处理,修改后代码。

    1 @Override
    2 public void onApplicationEvent(ContextRefreshedEvent event) {
    3 //root application context 没有parent,他就是老大.
    4 if(event.getApplicationContext().getParent() == null){
    5 //需要执行的逻辑代码,当spring容器初始化完成后就会执行该方法。
    6 }
    7 }

      方法二、  

      其实更简单的方法是使用注解:`@PostConstruct`,只需要在需要启动的时候执行的方法上标注这个注解就搞定了。

      方法三、

      方法实现InitializingBean或者ServletContextAware。
  • 相关阅读:
    WPF之感触
    C# WinForm 给DataTable中指定位置添加列
    MyEclipse 8.6 download 官方下载地址
    将博客搬至CSDN
    Building Microservices with Spring Cloud
    Building Microservices with Spring Cloud
    Building Microservices with Spring Cloud
    Building Microservices with Spring Cloud
    Building Microservices with Spring Cloud
    Building Microservices with Spring Cloud
  • 原文地址:https://www.cnblogs.com/lcngu/p/7591838.html
Copyright © 2011-2022 走看看