Spring Boot 获取上下文环境

在Spring中可以通过ContextLoader获取上下文环境

WebApplicationContext webApplicationContext = ContextLoader.getCurrentWebApplicationContext();

但是这种方式在Spring Boot是失效的。本文提供三种方案获取Spring Boot上下文环境。

1. 自动注入

@Autowired
WebApplicationContext webApplicationConnect;

2. 实现ApplicationContextAware接口

  /** * spring bean 工具类 * * @author simon * @create 2018-09-10 9:51 **/
    @Component
    public class SpringBeanTool implements ApplicationContextAware {
      /** * 上下文对象实例 */
      private static ApplicationContext applicationContext;

      @Override
      public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
      }
      /** * 获取applicationContext * * @return * applicationContext */
      public static ApplicationContext getApplicationContext() {
        return applicationContext;
      }

      /** * 通过name获取 Bean. * * @param name * bean name * @return * bean */
      public static Object getBean(String name){
        return getApplicationContext().getBean(name);
      }

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

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

3. 在启动类中设置

 public class SpringBeanTool {
        private static ApplicationContext applicationContext;

        public static ApplicationContext getApplicationContext(){
            return applicationContext;
        }

        public static void setApplicationContext(ApplicationContext applicationContext){
            SpringContextUtil.applicationContext = applicationContext;
        }

        public static  T getBean(String name){
            return (T)applicationContext.getBean(name);
        }

        public static  T getBean(Class clazz){
            return applicationContext.getBean(clazz);
        }
    }

启动类:

public static void main(String[] args) {
    ApplicationContext context = SpringApplication.run(Application.class, args);
    SpringBeanTool.setApplicationContext(context);
}

你可能感兴趣的:(Spring,Boot,2.0,Spring,Boot,2.0)