The Spring IoC dependency lookup types are as follows:
-
Lookup by Bean name (ID). In one Spring context, the name (ID) must be unique
-
Real-time search: Search now, get it now
-
Delay to find
Note: Spring applications can have multiple contexts
BeanFactory beanFactory = new ClassPathXmlApplicationContext("classpath:/dependency/lookupDemo.xml"); LookUpRealTime (beanFactory); // Delay lookUpLazyTime(beanFactory); Public static void lookUpRealTime(BeanFactory BeanFactory) {LookupUser LookupUser = (LookupUser) beanFactory.getBean("lookupUser"); System.out.println(lookupUser.toString()); * * *} / org. Springframework. Beans. Factory. The ObjectFactory * ObjectFactory, not generate new bean, ObjectFactoryCreatingFactoryBean FactoryBean will generate a new bean * * * may have a look, Public static void lookUpLazyTime(BeanFactory BeanFactory) {ObjectFactory<LookupUser> ObjectFactory = (ObjectFactory<LookupUser>) beanFactory.getBean("objectFactory"); LookupUser user = objectFactory.getObject(); System.out.println("lazy:"+user); }Copy the code
-
-
Lookup by Bean type
- Single Bean object
- Collection Bean object
BeanFactory beanFactory = new ClassPathXmlApplicationContext("classpath:/dependency/lookupDemo.xml"); // Look for a single object 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 < String, LookupUser > lookupUserMap = listableBeanFactory. GetBeansOfType (LookupUser. Class); System.out.println(lookupUserMap); }}Copy the code
-
Lookup by Bean name + type
-
Find according to Java annotations
- Single Bean object
- Collection Bean object
@target ({elementtype.type}) @Retention(retentionPolicy.runtime) public @interface Super {} BeanFactory beanFactory = new ClassPathXmlApplicationContext("classpath:/dependency/lookupDemo.xml"); / / consult collection types according to the annotation lookupByAnnotationCollection (the beanFactory); private static void lookupByAnnotationCollection(BeanFactory beanFactory) { if(beanFactory instanceof ListableBeanFactory){ ListableBeanFactory listableBeanFactory = (ListableBeanFactory) beanFactory; / / map, key, discover the custom annotation of Bean map < String, Object > lookupUserMap = listableBeanFactory. GetBeansWithAnnotation (Super) class); System.out.println(lookupUserMap); }}Copy the code