Spring Source Code Analysis-detailed analysis of BeanFactory system interfaces
The previous blog post analyzed Spring's Resource class Resouce. I started to analyze the IOC part of Spring today. As we all know, IOC is the most fascinating part of the Spring framework. Its most important interface is BeanFactory. BeanFactory has a huge inheritance and implementation system, and has many sub-interfaces and implementation classes. The goal of this blog post is to get rid of the source code, analyze the implementation and architecture of Spring, and make progress from it. During the reading process, you can refer to the Spring document for learning: Spring3.1.1 I have a limited level of English, some translations may be inappropriate, please note! 1. BeanFactory's basic class architecture (mainly interfaces): This is the basic class architecture of BeanFactory I have drawn. The powerful ApplicationContext system is not included here. I am going to put ApplicationContext in the next article for further analysis. Specifically: 1. BeanFactory, as a main interface, does not inherit any interfaces. It is now called a level-1 interface. 2. Three sub-interfaces inherit the sub-interfaces for function enhancement. These three subinterfaces are called level-2 interfaces. 3. ConfigurableBeanFactory can be called a third-level interface, which is used to enhance the HierarchicalBeanFactory. It also inherits another external interface SingletonBeanRegistry 4. ConfigurableListableBeanFactory is a more powerful interface, it inherits all the above interfaces and is called a level-4 interface. (These four interfaces are the basic interface system of BeanFactory. Continue, the following are two abstract classes and two implementation classes of the inheritance relationship: 5. AbstractBeanFactory as an abstract class, implements most of the three-level interface ableablebeanfactory functions. 6. AbstractAutowireCapableBeanFactory is also an abstract class, inherited from AbstractBeanFactory, and implemented the second-level interface AutowireCapableBeanFactory 7. defalistlistablebeanfactory inherited from AbstractAutowireCapableBeanFactory, which implements the most powerful four-level interface worker, and implements a foreign interface BeanDefinitionRegistry, which is not an abstract class. 8. Finally, the most powerful XmlBeanFactory inherits from DefaultListableBeanFactory and overwrites some functions to make itself more powerful. Conclusion: BeanFactory's class architecture seems complicated and chaotic. In fact, it is easy to understand from top to bottom. Ii. Let's take a look at BeanFactory's source code, BeanFactory, the ancestor of IOC. The cool interface won't be folded: copy the code package org. springframework. beans. factory; public interface BeanFactory {/*** is used to reference an instance or distinguish it from the Bean generated by the factory. That is to say, if the name of a FactoryBean is, $ a will get the Factory */String FACTORY_BEAN_PREFIX = "&";/** four getBean methods of different forms to get the instance */Object getBean (String name) throws BeansException; <T> T getBean (String name, Class <T> requiredType) throws BeansException; <T> T getBean (Class <T> requiredType) throws BeansException; Object getBean (String name, Object... args) throws BeansException; boolean containsBean (String name); // whether the boolean isSingleton (String name) throws exist; // whether it is a single instance boolean isPrototype (String name) throws NoSuchBeanDefinitionException; // is it a prototype (Multi-instance) boolean isTypeMatch (String name, Class <?> TargetType) throws NoSuchBeanDefinitionException; // whether the name and type match the Class <?> GetType (String name) throws NoSuchBeanDefinitionException; // obtain the type String [] getAliases (String name); // obtain the instance alias Based on the Instance name} copy the code details: 1. Four methods for obtaining instances. GetBean overload method. 2. Four judgment methods. Determine whether the instance exists, whether it is a Singleton, prototype, or whether the name type matches. 3. One method to obtain the type and one method to obtain the alias. Get type by name and alias by name. Easy to understand! Conclusion: These 10 methods are obviously a typical factory interface. 3. Factory ListableBeanFactory source code that can be listed one by Bean: public interface ListableBeanFactory extends BeanFactory {boolean containsBeanDefinition (String beanName ); // Number of BeanDefinition int getBeanDefinitionCount () for a given name; // returns the total number of BeanDefinition strings [] getBeanDefinitionNames () for the factory (); // return the name of all beans in the factory String [] getBeanNamesForType (Class <?> Type); // return all the names of beans (including subclasses) of the specified type./** return the name of the specified type. * If the value of includeNonSingletons is false, only the single-instance Bean is retrieved, if it is set to true, if it is not set to * allowEagerInit, "true" indicates immediate loading, and "false" indicates delayed loading. * Note: FactoryBeans are loaded immediately. */String [] getBeanNamesForType (Class <?> Type, boolean includeNonSingletons, boolean allowEagerInit); <T> Map <String, T> getBeansOfType (Class <T> type) throws BeansException; // Based on the type (including subclass) returns the Map <T> Map <String, T> getBeansOfType (Class <T> type, boolean includeNonSingletons, boolean allowEagerInit) throws BeansException; Map <String, object> getBeansWithAnnotation (Class <? Extends Annotation> annotationType) throws BeansException; // Based on the Annotation type, find all the Bean names with this Annotation and the Map of the Bean <A extends Annotation> A findAnnotationOnBean (String beanName, class <A> annotationType); // search for the specified Bean Based on the specified Bean name and annotation type}. Copy the code: 1. Three general operations related to BeanDefinition. Includes the total number of BeanDefinition, the set of names, and the set of names of the specified type. (BeanDefinition is a very important class in Spring. Each BeanDefinition instance contains all the attributes of a class in the Spring factory .) 2. Two getBeanNamesForType overload methods. Obtains the names of all Bean corresponding to a specified type (including subclass. 3. Two getBeansOfType overload methods. Return the Map of the specified Bean name and Bean Based on the type (including subclass. 4. Two methods related to annotation search. Search for the Bean name and Bean Map based on the annotation type. And searches for the specified Bean Based on the specified Bean name and annotation type. Summary: As shown in the name of this factory interface, the biggest feature of this factory interface is to list all instances that can be produced by the factory. Of course, the factory does not directly provide methods to return all instances, and this is not necessary. It can return all instances of the specified type. In addition, you can get the names of all beans in the factory through getBeanDefinitionNames (), and then get all beans based on these names. This factory interface extends the BeanFactory function. As the BeanFactory second-level interface mentioned above, there are nine unique methods that extend the features with BeanDefinition, provides various operations related to BeanDefinition, BeanName, and annotation. It can return the Bean set based on the condition, which is the origin of its name-ListableBeanFactory. 4. Layered Bean factory-HierarchicalBeanFactory source code: copy the code public interface HierarchicalBeanFactory extends BeanFactory {BeanFactory getParentBeanFactory (); // return the parent factory boolean containsLocalBean (String name) of the Bean factory ); // whether the local factory contains this Bean} copy code: 1. the first method returns the parent factory of the Bean factory. This method achieves the layer of the factory. 2. The second method determines whether the local factory contains the Bean (ignore all other parent factories ). This is also the embodiment of stratified thinking. Summary: This factory interface is very simple and implements the layer of Bean factory. This factory interface also inherits from beanfacodid and is also a level-2 interface. Compared with the parent interface, it only extends one important feature-factory hierarchy. 5. AutowireCapableBeanFactory source code: copy the code public interface AutowireCapableBeanFactory extends BeanFactory {int AUTOWIRE_NO = 0; // This constant indicates that the factory has not automatically assembled Bean int AUTOWIRE_BY_NAME = 1; // indicates that int AUTOWIRE_BY_TYPE = 2 is automatically assembled according to the name; // indicates that int AUTOWIRE_CONSTRUCTOR = 3 is automatically assembled according to the type; // indicates fast assembly according to the construction method @ Deprecated int AUTOWIRE_AUTODETECT = 4; // indicates automatic assembly through the internal class of Bean (no translation error ...) spring3.0 is deprecated. <T> T createBean (Class <T> beanClass) throws BeansException; // create a brand new Bean instance void autowireBean (Object existingBean) throws BeansException Based on the specified Class; // specify an Object, automatic Assembly Based on annotations, post-processors, etc./** assemble this unprocessed Object based on BeanDefinition of Bean name, and execute the echo and various post-processors. */Object configureBean (Object existingBean, String beanName) throws BeansException;/** the specified dependency descriptor defined by the decomposition Bean in the factory */Object resolveDependency (DependencyDescriptor descriptor, String beanName) throws BeansException;/** create a new Bean instance */Object createBean (Class <?> BeanClass, int autowireMode, boolean dependencyCheck) throws BeansException;/** similar to the above, but slightly different. */Object autowire (Class <?> BeanClass, int autowireMode, boolean dependencyCheck) throws BeansException;/** automatically assemble according to name or type */void autowireBeanProperties (Object existingBean, int autowireMode, boolean dependencyCheck) throws BeansException; /** automatically assemble */void applyBeanPropertyValues (Object existingBean, String beanName) throws BeansException;/** initialize a Bean... */Object initializeBean (Object existingBean, String beanName) th Rows BeansException;/** execute BeanPostProcessors */Object attributes (Object existingBean, String beanName) throws BeansException before initialization;/** execute BeanPostProcessors */Object attributes (Object existingBean, string beanName) throws BeansException;/** break down the specified dependency */Object resolveDependency (DependencyDescriptor descriptor, String beanNam E, Set <String> autowiredBeanNames, TypeConverter typeConverter) throws BeansException;} copy the code: 1. A total of five static immutable constants are used to specify the Assembly policy, one of the constants is discarded by Spring3.0. One constant indicates that automatic assembly is not performed. The other three constants indicate different Assembly policies based on the name, type, and constructor. 2. 8 methods related to automatic assembly are complicated. Let's try again when studying the specific meaning. 3. Two Methods for executing BeanPostProcessors. 4. Two Methods for decomposing specified dependencies: This factory interface inherits from beanfacoprocessor, which extends the automatic assembly function and defines BeanDefinition Assembly Bean, pre-execution, post-processor, and so on based on the class. 6. Complex Configuration Bean factory-ConfigurableBeanFactory source code: copy the code public interface ConfigurableBeanFactory extends container, SingletonBeanRegistry {String SCOPE_SINGLETON = "singleton"; // singleton String SCOPE_PROTOTYPE = "prototype "; // prototype/** use the getParentBeanFactory method of HierarchicalBeanFactory interface */void setParentBeanFactory (BeanFactory parentBeanFactory) throws IllegalStateException;/** set and return the class loader of the factory */ Void Uploader (ClassLoader beanClassLoader); ClassLoader getBeanClassLoader ();/** set and return a temporary class loader */void Uploader (ClassLoader tempClassLoader); ClassLoader getTempClassLoader (); /** set and whether to cache metadata. If the value is false, the instance will be reloaded (hot-loaded) from the classloader each time it is requested */void setCacheBeanMetadata (boolean cacheBeanMetadata ); boolean isCacheBeanMetadata (); // whether metadata is cached/** Bean expression splitter */void setBeanExpressionResolver (Bean ExpressionResolver resolver); BeanExpressionResolver getBeanExpressionResolver ();/** set and return a conversion Service */void setConversionService (ConversionService conversionService); ConversionService getConversionService (); /** set the property to edit the register... */void addPropertyEditorRegistrar (PropertyEditorRegistrar registrar);/** register common Attribute Editor */void registerCustomEditor (Class <?> RequiredType, Class <? Extends PropertyEditor> propertyEditorClass);/** use the General Editor registered in the factory to initialize the specified property editing Registrar */void copyRegisteredEditorsTo (PropertyEditorRegistry registry ); /** set and obtain a type converter */void setTypeConverter (TypeConverter typeConverter); TypeConverter getTypeConverter ();/** add an embedded StringValueResolver */void Merge (StringValueResolver valueResolver ); string resolveEmbeddedValue (String value); // decomposition refers Set the embedded value void addBeanPostProcessor (BeanPostProcessor beanPostProcessor); // set a Bean post-processor int getBeanPostProcessorCount (); // return the number of post-Bean processors void registerScope (String scopeName, scope scope); // registration range String [] getRegisteredScopeNames (); // return the registration range name Scope getRegisteredScope (String scopeName); // return the specified range AccessControlContext getAccessControlContext (); // return a secure access context void copyConfigurationFrom (ConfigurableBeanFa Ctory otherFactory); // copy all related configurations from other factories/** register an alias for the specified Bean */void registerAlias (String beanName, String alias) throws BeanDefinitionStoreException; void resolveAliases (StringValueResolver valueResolver); // removes all aliases Based on the specified StringValueResolver/** returns the Bean definition after the specified Bean is merged */BeanDefinition partition (String beanName) throws handler; boolean isFactoryBean (String name) throws No SuchBeanDefinitionException; // determines whether the specified Bean is a factory Bean void setCurrentlyInCreation (String beanName, boolean inCreation); // sets whether a Bean is creating boolean isCurrentlyInCreation (String beanName ); // return whether the specified Bean has been successfully created void registerDependentBean (String beanName, String dependentBeanName); // register a bean String [] getDependentBeans (String beanName) dependent on the specified Bean ); // return the consumer Bean name String [] getDependenciesForBean (String beanNa Me); // return the void destroyBean (String beanName, Object beanInstance) of all Bean dependent on the specified Bean; // destroy the specified Bean void destroyScopedBean (String beanName ); // destroy the Bean void destroySingletons () in the specified range; // destroy all Singleton classes} copy the code. Before introducing it, let's take a look at the source code of the SingletonBeanRegistry interface: copy the code public interface SingletonBeanRegistry {void registerSingleton (String beanName, Object singletonObject); // register a singleton Class Object getSingleton (String beanName) in the container; // return the corresponding name Singleton boolean containsSingleton (String beanName); // whether the given name corresponds to the singletonnames (); // return the name int getSingletonCount () of all singleclasses in the container; // return the number of singletoncount classes registered in the container.} copy the code and you can see that the SingletonBeanRegistry interface is very simple, five methods to implement the single-instance class registration function. ConfigurableBeanFactory inherits both HierarchicalBeanFactory and SingletonBeanRegistry interfaces, that is, it inherits both the hierarchical and single-instance class registration functions. Specifically: 1 and 2 static immutable constants represent Singleton classes and prototype classes respectively. 2. One method for setting the parent factory is complementary to the getParentBeanFactory method of the HierarchicalBeanFactory interface. 3. Four methods related to the Class Loader: get/set factory class loader and get/set temporary class loader. 4. Two Methods for setting and caching metadata (hot loading switch ). 5. 11 methods for handling Bean registration, loading, and other details, including: bean expression splitter, conversion service, property edit register, property Editor, property edit register, type converter, embedded string splitter 6, two processing Bean post-processor methods. 7. Three methods related to the registration scope. 8. One method that returns the security access context, and one method that copies all related configurations from other factories. 9. Two methods related to Bean aliases and one method for returning the merged Bean definition. 10. One method for determining whether the Bean is a factory Bean and two methods related to the current Bean creation time. 11. Three methods related to Bean dependencies and three methods related to Bean destruction. Summary: this huge factory interface inherits from HierarchicalBeanFactory and SingletonBeanRegistry, and has 37 additional methods !!! (I'm going crazy.) These 37 methods contain details about how to create and register a Bean in a factory. The name of this factory is ableablebeanfactory! Count the number of ableablebeanfactory methods. There are 37 methods, 2 HierarchicalBeanFactory methods, 5 SingletonBeanRegistry methods, and 10 BeanFactory methods on the Grandmaster interface. There are 54 methods in total! Although there are many methods, it is still well organized!