SpringBoot 五种获取ApplicationContext的方式

之前每次想要获取Spring上下文【ApplicationContext】的时候,都去现查方案。本文针对获取Spring ApplicationContext的方式做了梳理,总结。

1. 概念

ApplicationContext是什么?

简单来说就是Spring中的容器,可以用来获取容器中的各种bean组件,注册监听事件,加载资源文件等功能

2. 获取ApplicationContext的方式

2.1. 创建工具类

通过此工具类,可以方便的获取bean组件, 获取配置信息等

import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.core.env.Environment;

public class SpringUtil {
    private static ApplicationContext applicationContext = null;
    private static Environment environment = null;

    public static void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        if (SpringUtil.applicationContext == null) {
            SpringUtil.applicationContext = applicationContext;
            environment = applicationContext.getEnvironment();
            //TODO 设置后,可以做一些操作
        }
    }

    //获取applicationContext
    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    public static Environment getEnvironment() {
        return environment;
    }

    //通过name获取 Bean.
    public static Object getBean(String name) {
        return getApplicationContext().getBean(name);

    }

    //通过class获取Bean.
    public static <T> T getBean(Class<T> clazz) {
        return getApplicationContext().getBean(clazz);
    }

    //通过name,以及Clazz返回指定的Bean
    public static <T> T getBean(String name, Class<T> clazz) {
        return getApplicationContext().getBean(name, clazz);
    }

    public static String getString(String key) {
        return environment.getProperty(key);
    }

    public static int getInt(String key) {
        return NumberUtils.toInt(environment.getProperty(key));
    }

    public static long getLong(String key) {
        return NumberUtils.toLong(environment.getProperty(key));
    }

    public static boolean getBoolean(String key) {
        return BooleanUtils.toBoolean(environment.getProperty(key));
    }
}

方式1: 实现ApplicationContextInitializer接口

实现接口后,将此类注入到Spring容器中,有两种方式。当然也可以直接调用静态方法

  • 第一种: 在此类上加`@Component`注解

  • 第二种:在 `resources/META-INF/spring.factories`文件中添加以下配置:  org.springframework.context.ApplicationContextInitializer=CustomerApplicationContextInitializer的路径

实现ApplicationContextInitializer的源码示例:


public class CustomApplicationContextInitializer implements ApplicationContextInitializer {
  @Override
  public void initialize(ConfigurableApplicationContext applicationContext) {    
     SpringBeanUtils.setApplicationContext(applicationContext);
  }
}

方式2. 实现ApplicationListener接口

实现接口后,将此类注入到Spring容器中,有两种方式。当然也可以直接调用静态方法

  • 第一种: 在此类上加`@Component`注解

  • 第二种:在 `resources/META-INF/spring.factories`文件中添加以下配置:  org.springframework.context.ApplicationContextInitializer=CustomerApplicationListener的路径

实现ApplicationListener的源码示例:


public class CustomApplicationListener implements ApplicationListener<ApplicationContextEvent> {
  @Override
  public void onApplicationEvent(ApplicationContextEvent event) {        
     SpringBeanUtils.setApplicationContext(event.getApplicationContext());
  }
}

方式3. 在启动类main方法中设置

@SpringBootApplication
@EnableSwagger2
public class Application {
    public static void main(String[] args) {
        ConfigurableApplicationContext applicationContext = SpringApplication.run(WangMikeSpringApplication.class, args);        
        SpringBeanUtils.setApplicationContext(applicationContext);
    }
}

方式4. 实现ApplicationContextAware接口

@Component
public class SpringBeanUtils implements ApplicationContextAware {
    private static ApplicationContext applicationContext;
    public  void setApplicationContext(ApplicationContext applicationContext){
        SpringBeanUtils.applicationContext = applicationContext;
    }

    public static ApplicationContext getApplicationContext(
        return applicationContext;
    }
}

方式5. 直接通过@Resource注解注入

@Component
@Order(value = 1)
@Slf4j
public class AppStartRunner implements org.springframework.boot.ApplicationRunner {
    protected static Logger logger = LoggerFactory.getLogger(AppStartRunner.class);

    @Resource
    ApplicationContext applicationContext;