Interpretation of spring beans source code-the ancestor of ioc containers-DefaultListableBeanFactory
The implementation of spring Ioc container is beanfactory at the root, but it can actually be used as an independent ioc container or DefaultListableBeanFactory. So it can be said that DefaultListableBeanFactory is the ancestor of the whole spring ioc, the study reveals that the past and current generations play an important role in understanding the concept of spring ioc. 1. DefaultListableBeanFactory: The ListableBeanFactory and BeanDefinitionRegistry interfaces are implemented by default. Based on the bean definition object, the interface is a mature bean factroy. The most typical application is to register all the definitions before accessing the bean (possibly from the bean definition configuration file ). Using a pre-created bean to define metadata objects, querying the bean definition from the local bean definition table does not cost much. DefaultListableBeanFactory can be used as a separate beanFactory or as a parent class for custom beanFactory. Note: The Parser of bean definition in a specific format can be implemented by itself, or you can use the original parser, such as PropertiesBeanDefinitionReader and XmLBeanDefinitionReader. 2. defaultListableBeanFactory inheritance relationship (Image Source: http://www.myexception.cn/software-architecture-design/925888.html) 3. all right, start to enter the ultlistablebeanfactory world direct inheritance relationship: public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactory implements attributes, BeanDefinitionRegistry, Serializable {} 3.1 static method private static Class <?> JavaxInjectProviderClass = null; static {try {javaxInjectProviderClass = ClassUtils. forName ("javax. inject. provider ", DefaultListableBeanFactory. class. getClassLoader ();} catch (ClassNotFoundException ex) {// JSR-330 API not available-Provider interface simply not supported then .}} spring provides some practical integrated tool classes such as ClassUtils. ClassUtils provides practical methods for classes and is mainly used within the Framework. For more information about the tool methods of classes, see apache commons lang. Commons LangThe standard Java libraries fail to provide enough methods for manipulation of its core classes. apache Commons Lang provides these extra methods. lang provides a host of helper utilities for the java. lang API, notably String manipulation methods, basic numerical methods, object reflection, concurrency, creation and serialization and System properties. additionally it contains basic en Hancements to java. util. date and a series of utilities dedicated to help with building methods, such as hashCode, toString and define sclassutils. the forName method is class. forname rewriting returns an instance of a class. For the difference, see the source code. The above static method returns an instance of javax. inject. Provider, so let's unveil javax. inject. Provider to see what role it actually plays. Syntax: public interface Provider <T> provides a T instance. it is usually used as a parent interface of the dependency injection container. any type of T can be injected, or Provider <T> can be injected. compared with direct injection T, injection Provider <T> has the following functions: retrieving multiple instances. latencies or selective retrieval of an instance. break the cycle dependency. abstract scope, which can retrieve an instance from a smaller scope containing the scope. Instance code: class Car {@ Inject Car (Provider <Seat> seatProvider) {Seat driver = seatProvider. get (); Seat passenger = seatProvider. get ();...}} 3.2 method inherited from AbstractAutowireCapableBeanFactory: AbstractAutowireCapableBeanFactory function: Provide bean creation (with construct method), attribute value injection, binding (including automatic binding) and initialization. process bean reference during runtime, parse the management set, and call the initialization method. The main template method to be implemented by subclass is AutowireCapableBeanFactory. resolveDependency (DependencyDescriptor, String, Set, TypeConverter). This method is used to implement automatic binding of types. abstrultlistablebeanfactory implements AbstractAutowireCapableBeanFactory. copyConfigurationFrom @ Override public void copyConfigurationFrom (ConfigurableBeanFactory otherFactory) {super. copyConfigurationFrom (otherFactory); if (otherFactory instanceof DefaultListableBeanFactory) {Defalistlistablebeanfactory otherListableFactory = (defalistlistablebeanfactory) otherFactory; this. allowBeanDefinitionOverriding = otherListableFactory. allowBeanDefinitionOverriding; this. allowEagerClassLoading = otherListableFactory. allowEagerClassLoading; this. autowireCandidateResolver = otherListableFactory. autowireCandidateResolver; this. resolvableDependencies. putAll (otherListableFactory. reso LvableDependencies);} among them: allowBeanDefinitionOverriding defines whether to allow different bean definition with the same name to register again; allowEagerClassLoading defines whether to allow loading of eager classes (relative to lazy, even delayed loading of initialized beans. AutowireCandidateResolver is a policy interface used to determine whether a specific bean definition meets the requirements for Automatic Binding of a specific dependency. The method is as follows: // SimpleAutowireCandidateResolver implements AutowireCandidateResolver @ Override public boolean isAutowireCandidate (BeanDefinitionHolder bdHolder, DependencyDescriptor descriptor) {return bdHolder. getBeanDefinition (). isAutowireCandidate ();} // GenericTypeAwareAutowireCandidateResolver implements AutowireCandidate Resolver @ Override public boolean isAutowireCandidate (BeanDefinitionHolder bdHolder, DependencyDescriptor descriptor) {if (! BdHolder. getBeanDefinition (). isAutowireCandidate () {// if explicitly false, do not proceed with any other checks return false;} return (descriptor = null | checkGenericTypeMatch (bdHolder, descriptor ));} resolvableDependencies: a set of automatically bound values of the dependency type. The copyConfigurationFrom method of AbstractAutowireCapableBeanFactory: @ Override public void copyConfigurationFrom (abstrablebeanfactory otherFactory) {super. copyConfigurationFrom (otherFactory); if (otherFactory instanceof AbstractAutowireCapableBeanFactory) {AbstractAutowireCapableBeanFactory otherAutowireFactory = (AbstractAutowireCapableBeanFactory) otherFactory; this. instantiationStrategy = otherAuto WireFactory. instantiationStrategy; this. allowCircularReferences = otherAutowireFactory. allowCircularReferences; this. ignoredDependencyTypes. addAll (otherAutowireFactory. ignoredDependencyTypes); this. ignoredDependencyInterfaces. addAll (otherAutowireFactory. ignoredDependencyInterfaces);} among them, instantiationStrategy is the policy for creating bean instances. Default Value: private InstantiationStrategy instantiationStrategy = new CglibSubcl AssingInstantiationStrategy (); allowCircularReferences determines whether to automatically try to parse the bean referenced by the loop. IgnoredDependencyTypes defines the dependency types to be ignored during dependency check and automatic binding. It is a group of class objects, such as string. The default value is none. IgnoredDependencyInterfaces defines the dependency interfaces to be ignored during dependency check and automatic binding. It is a group of class objects. By default, only the beanFactory interface is ignored. The implementation of copyConfigurationFrom in the parent class AbstractBeanFactory is as follows: @ Override public void copyConfigurationFrom (abstrablebeanfactory otherFactory) {Assert. notNull (otherFactory, "BeanFactory must not be null"); setBeanClassLoader (otherFactory. getBeanClassLoader (); setCacheBeanMetadata (otherFactory. isCacheBeanMetadata (); setBeanExpressionResolver (otherFactory. getBeanExpressionResolver (); if (otherFactory insta Nceof AbstractBeanFactory) {AbstractBeanFactory otherw.actfactory = (AbstractBeanFactory) otherFactory; this. customEditors. putAll (otherpolicactfactory. customEditors); this. propertyEditorRegistrars. addAll (otherpolicactfactory. propertyEditorRegistrars); this. beanPostProcessors. addAll (otherpolicactfactory. beanPostProcessors); this. hasInstantiationAwareBeanPostProcessors = this. hasInstantiationAwa ReBeanPostProcessors | otherw.actfactory. hasInstantiationAwareBeanPostProcessors; this. hasDestructionAwareBeanPostProcessors = this. hasDestructionAwareBeanPostProcessors | otherw.actfactory. hasDestructionAwareBeanPostProcessors; this. scopes. putAll (otherpolicactfactory. scopes); this. securityContextProvider = otherpolicactfactory. securityContextProvider;} else {setTypeConverter (otherFactor Y. getTypeConverter () ;}among them, customEditors is a custom attribute editor and applies to all beanFactory beans. The register of the propertyEditorRegistrars property Editor, which is used by all beans of the beanFactory. BeanPostProcessors that is applied when beanPostProcessors creates a bean. HasInstantiationAwareBeanPostProcessors indicates whether any InstantiationAwareBeanPostProcessors is registered. HasDestructionAwareBeanPostProcessors indicates whether any DestructionAwareBeanPostProcessorsscopes is registered: a collection of domain identifiers and key-value pairs of the corresponding domain. Security context used by securityContextProvider to run SecurityManager. 3.3 The ListableBeanFactory method inherited from the ListableBeanFactory interface is an extended interface of the beanFactory interface. It can enumerate all bean instances, rather than the client can query all instances by name. This interface can be implemented to pre-load beanfactory defined by all beans. This interface defines several methods to access the Bean basic information in the container, such as viewing the number of beans, obtaining the configuration name of a type of Bean, and checking whether a Bean is included in the container; containsBeanDefinition (String beanName) Check if this bean factory contains a bean definition with the given name. findAnnotationOnBean (String beanName, Class <A> annotationType) Find a Annotation of annotationType on the specified bean, traversing its interfaces and super classes if no annotation can be found on the given class Itself. getBeanDefinitionCount () Return the number of beans defined in the factory. getBeanDefinitionNames () Return the names of all beans defined in this factory. getBeanNamesForType (Class <?> Type) Return the names of beans matching the given type (including subclasses), judging from either bean definitions or the value of getObjectType in the case of FactoryBeans. getBeanNamesForType (Class <?> Type, boolean comment denonsingletons, boolean allowEagerInit) Return the names of beans matching the given type (including subclasses), judging from either bean definitions or the value of getObjectType in the case of FactoryBeans. getBeansOfType (Class <T> type) Return the bean instances that match the given object type (including subclasses), judging from either bean definitions or the value of getO BjectType in the case of FactoryBeans. getBeansOfType (Class <T> type, boolean includeNonSingletons, boolean allowEagerInit) Return the bean instances that match the given object type (including subclasses ), judging from either bean definitions or the value of getObjectType in the case of FactoryBeans. getBeansWithAnnotation (Class <? Extends Annotation> annotationType) Find all beans whose Class has the supplied Annotation type. 3.4 The ConfigurableListableBeanFactory method inherited from the ConfigurableListableBeanFactory interface inherits both ListableBeanFactory, AutowireCapableBeanFactory and ableablebeanfactory, and provides convenient methods for analyzing and modifying bean definitions, pre-instantiation of a single instance is also provided. Void freezeConfiguration () Freeze all bean definitions, signalling that the registered bean definitions will not be modified or post-processed any further. beanDefinition destroy (String beanName) Return the registered BeanDefinition for the specified bean, allowing access to its property values and constructor argument value (which can be modified during bean factory post-processing ). vo Id ignoreDependencyInterface (Class <?> Ifc) Ignore the given dependency interface for autowiring. void ignoreDependencyType (Class <?> Type) Ignore the given dependency type for autowiring: for example, String. boolean isAutowireCandidate (String beanName, DependencyDescriptor descriptor) Determine whether the specified bean qualifies as an autowire candidate, to be injected into other beans which declare a dependency of matching type. boolean isConfigurationFrozen () Return whether this factory's bean definitions are frozen, I. e. Void preInstantiateSingletons () Ensure that all non-lazy-init singletons are instantiated, also considering FactoryBeans. void registerResolvableDependency (Class <?> DependencyType, Object autowiredValue) Register a special dependency type with corresponding autowired value. 3.5 method of inheriting from BeanDefinitionRegistry interface BeanDefinitionRegistry: Each <bean> node element in the Spring configuration file is represented by a BeanDefinition object in the Spring container, which describes Bean configuration information. The BeanDefinition Registry interface provides the method to manually register the BeanDefinition object to the container. Boolean containsBeanDefinition (String beanName) Check if this registry contains a bean definition with the given name. beanDefinition getBeanDefinition (String beanName) Return the BeanDefinition for the given bean name. int getBeanDefinitionCount () Return the number of beans defined in the registry. string [] getBeanDefinitionNames () Return the names of all beans defined in this registry. boolean I SBeanNameInUse (String beanName) Determine whether the given bean name is already in use within this registry, I. e. void registerBeanDefinition (String beanName, BeanDefinition beanDefinition) Register a new bean definition with this registry. void removeBeanDefinition (String beanName) Remove the BeanDefinition for the given name. 3.6 serialization supports private void writeObject (java. io. objectOutputStream out) thr Ows IOException private void readObject (java. io. objectInputStream in) throws IOException, ClassNotFoundException; private void readObjectNoData () throws ObjectStreamException; 4 Summary: Implementation of the spring Ioc container. The root cause is beanfactory, but it can actually be used as an independently usable ioc container or DefaultListableBeanFactory. So it can be said that DefaultListableBeanFactory is the ancestor of the entire spring ioc, the study reveals that the past and current generations play an important role in understanding the concept of spring ioc. The DefaultListableBeanFactory function is implemented through interfaces that implement specific functions. AbstractAutowireCapableBeanFactory Enables automatic property binding. ConfigurableListableBeanFactory provides convenient methods for analyzing and modifying bean definitions, and also provides pre-instantiation of a single instance. ListableBeanFactory provides the function of enumerating all bean instances, rather than obtaining all the instances by the client through one query by name. BeanDefinitionRegistry provides beanDefinition management.