1. 程式人生 > >Spring boot 梳理 - SpringBoot中注入ApplicationContext物件的三種方式

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!"); } } }