Spring boot 梳理 - SpringBoot中注入ApplicationContext对象的三种方式

  1. 直接注入(Autowired)
    1. @Configuration
      public class OAConfig {
          @Autowired
          private ApplicationContext applicationContext;
          
          @Bean
          public PersonUtils personUtil(){
              boolean bool=applicationContext.containsBean("aa");
              System.out.println("containsBean:aa:"+bool);
              return new PersonUtils();
          }
      }
      
      
      
      @Component
      public class User {
      
          @Autowired
          private ApplicationContext applicationContext;
      }

       

  2. 构造器方法注入
    1. @Component
      public class User{
          private ApplicationContext applicationContext;
      
          public User(ApplicationContext applicationContext) {
              this.applicationContext = applicationContext;
          }
      }

       

  3. 手动构建类实现接口
    1. /**
       * Spring的ApplicationContext的持有者,可以用静态方法的方式获取spring容器中的bean
       *
       * @author yj
       * @date 2018年5月27日 下午6:32:11
       */
      @Component
      public class SpringContextHolder implements ApplicationContextAware {
      
          private static ApplicationContext applicationContext;
      
          @Override
          public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
              SpringContextHolder.applicationContext = applicationContext;
          }
      
          public static ApplicationContext getApplicationContext() {
              assertApplicationContext();
              return applicationContext;
          }
      
          @SuppressWarnings("unchecked")
          public static <T> T getBean(String beanName) {
              assertApplicationContext();
              return (T) applicationContext.getBean(beanName);
          }
      
          public static <T> T getBean(Class<T> requiredType) {
              assertApplicationContext();
              return applicationContext.getBean(requiredType);
          }
      
          private static void assertApplicationContext() {
              if (SpringContextHolder.applicationContext == null) {
                  throw new RuntimeException("applicaitonContext属性为null,请检查是否注入了SpringContextHolder!");
              }
          }
      
      }

       

posted on 2018-12-27 22:06  手握太阳  阅读(8679)  评论(0编辑  收藏  举报

导航