Spring IoC依賴查找類型如下:
-
根據(jù)Bean名稱(id)查找,在Spring的一個(gè)上下文中誊锭,名稱(id)必須唯一
實(shí)時(shí)查找:馬上查找,馬上所得
-
延遲查找
注:spring 應(yīng)用可以有多個(gè)上下文
BeanFactory beanFactory = new ClassPathXmlApplicationContext("classpath:/dependency/lookupDemo.xml"); //實(shí)時(shí)查找 lookUpRealTime(beanFactory); //延遲查找 lookUpLazyTime(beanFactory); /** * spring ioc實(shí)時(shí)查找 */ 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則會(huì)生成新的bean * ObjectFactoryCreatingFactoryBean ** 可以看下實(shí)現(xiàn)甫何,一個(gè)很歡樂的設(shè)計(jì)模式 * */ public static void lookUpLazyTime(BeanFactory beanFactory) { ObjectFactory<LookupUser> objectFactory = (ObjectFactory<LookupUser>) beanFactory.getBean("objectFactory"); LookupUser user = objectFactory.getObject(); System.out.println("lazy:"+user); }
-
根據(jù)Bean類型查找
- 單個(gè)Bean對(duì)象
- 集合Bean對(duì)象
BeanFactory beanFactory = new ClassPathXmlApplicationContext("classpath:/dependency/lookupDemo.xml"); //查找單個(gè)對(duì)象 lookUpByType(beanFactory); //查找集合對(duì)象 lookupByCollectionType(beanFactory); public static void lookUpByType(BeanFactory beanFactory) { LookupUser user = beanFactory.getBean(LookupUser.class); System.out.println(user.toString()); } /** * 復(fù)合類型查找 */ private static void lookupByCollectionType(BeanFactory beanFactory) { if(beanFactory instanceof ListableBeanFactory){ ListableBeanFactory listableBeanFactory = (ListableBeanFactory) beanFactory; //map穆咐,ke Map<String, LookupUser> lookupUserMap = listableBeanFactory.getBeansOfType(LookupUser.class); System.out.println(lookupUserMap); } }
根據(jù)Bean名稱+類型查找
-
根據(jù)Java注解查找
- 單個(gè)Bean對(duì)象
- 集合Bean對(duì)象
//自定義注解 @Target({ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) public @interface Super { } BeanFactory beanFactory = new ClassPathXmlApplicationContext("classpath:/dependency/lookupDemo.xml"); //根據(jù)注解查找集合類型 lookupByAnnotationCollection(beanFactory); private static void lookupByAnnotationCollection(BeanFactory beanFactory) { if(beanFactory instanceof ListableBeanFactory){ ListableBeanFactory listableBeanFactory = (ListableBeanFactory) beanFactory; //map,key, 查找符合自定義注解的Bean Map<String, Object> lookupUserMap = listableBeanFactory.getBeansWithAnnotation(Super.class); System.out.println(lookupUserMap); } }