Spring IoC依赖查找

Spring IoC依赖查找类型如下:

  1. 根据Bean名称(id)查找,在Spring的一个上下文中,名称(id)必须唯一

    • 实时查找:马上查找,马上所得

    • 延迟查找

      注:spring 应用可以有多个上下文

        BeanFactory beanFactory = new ClassPathXmlApplicationContext("classpath:/dependency/lookupDemo.xml");
        //实时查找
        lookUpRealTime(beanFactory);
        //延迟查找
        lookUpLazyTime(beanFactory);
    
         /**
         * spring ioc实时查找
         */
        public static void lookUpRealTime(BeanFactory beanFactory) {
            LookupUser lookupUser = (LookupUser) beanFactory.getBean("lookupUser");
            System.out.println(lookupUser.toString());
        }
        
        /**
         *org.springframework.beans.factory.ObjectFactory
         * ObjectFactory,没有生成新的bean, FactoryBean则会生成新的bean
         * ObjectFactoryCreatingFactoryBean ** 可以看下实现,一个很欢乐的设计模式
         *
         */
        public static void lookUpLazyTime(BeanFactory beanFactory) {
    
            ObjectFactory objectFactory = (ObjectFactory) beanFactory.getBean("objectFactory");
            LookupUser user = objectFactory.getObject();
            System.out.println("lazy:"+user);
    
        }
    
  2. 根据Bean类型查找

    • 单个Bean对象
    • 集合Bean对象
        BeanFactory beanFactory = new ClassPathXmlApplicationContext("classpath:/dependency/lookupDemo.xml");
        //查找单个对象
        lookUpByType(beanFactory);
        //查找集合对象
        lookupByCollectionType(beanFactory);
        
        
        public static void lookUpByType(BeanFactory beanFactory) {
         LookupUser user = beanFactory.getBean(LookupUser.class);
         System.out.println(user.toString());
        }
    
         /**
         * 复合类型查找
         */
        private static void lookupByCollectionType(BeanFactory beanFactory) {
            if(beanFactory instanceof ListableBeanFactory){
                ListableBeanFactory listableBeanFactory = (ListableBeanFactory) beanFactory;
                //map,ke
                Map lookupUserMap = listableBeanFactory.getBeansOfType(LookupUser.class);
                System.out.println(lookupUserMap);
            }
        }
    
  3. 根据Bean名称+类型查找

  4. 根据Java注解查找

    • 单个Bean对象
    • 集合Bean对象
    //自定义注解
    @Target({ElementType.TYPE})
    @Retention(RetentionPolicy.RUNTIME)
    public @interface Super {
    }
    
     BeanFactory beanFactory = new ClassPathXmlApplicationContext("classpath:/dependency/lookupDemo.xml");
     //根据注解查找集合类型
     lookupByAnnotationCollection(beanFactory);
     
    private static void lookupByAnnotationCollection(BeanFactory beanFactory) {
        if(beanFactory instanceof ListableBeanFactory){
            ListableBeanFactory listableBeanFactory = (ListableBeanFactory) beanFactory;
            //map,key, 查找符合自定义注解的Bean
            Map lookupUserMap = listableBeanFactory.getBeansWithAnnotation(Super.class);
            System.out.println(lookupUserMap);
        }
    }
    

你可能感兴趣的:(Spring IoC依赖查找)