IOC container description -BeanFactory

14.1 BeanFactory and its subinterfaces

BeanFactory-***

  • BeanFactory is the most basic root container for managing beans in the SpringFramework, and the extensions below are designed to implement some additional features (hierarchy, searchability, configurability, and so on).

  • The Scope of the Bean is defined in the BeanFactory and is explicitly declared by the @Scope annotation.

  • The BeanFactory itself is the registry for all beans, and all beans are ultimately created and saved in the BeanFactory.

    In addition, BeanFactory also integrates the configuration of application components, but this concept is relatively old. After SpringFramework 3.1, there is a new concept called Environment, which is the real Environment and configuration store.

  • Support for multiple types of configuration sources, such as XML and annotation-driven. See BeanDefinition

  • The BeanFactory itself can support parent-child structures.

  • BeanFactory has a complete lifecycle control mechanism.


HierarchicalBeanFactory

It is a hierarchical BeanFactory, from which the BeanFactory has a parent-child structure.

  • Common API interfaces:

    • The parent BeanFactory object is set, you can useConfigurableBeanFactoryThe interfacesetParentBeanFactory()Methods; toGets the parent BeanFactory object, you can usegetParentBeanFactory()Methods.
    • The other method in the interface iscontainsLocalBean(String name), it isChecks whether the specified Bean exists in the current local containerInstead of going up to the parent BeanFactory.
    • getBean()Methods willStarts at the current BeanFactory to find if the specified Bean existsIf the parent BeanFactory cannot be found, the parent BeanFactory will be returned until it is found, or the parent BeanFactory will be thrown if it cannot be found at allNoSuchBeanDefinitionException
  • If there is a specified Bean in the current BeanFactory, can there be one in the parent BeanFactory?

    May be! Because even if there are parent-child relationships, they are essentially different containers, it is possible to find multiple identical beans.

    In other words, the Singleton declared in @Scope is Singleton only in one container, but with the hierarchical structure, it is not Singleton for the entire container.


ListableBeanFactory

  • Applies to a BeanFactory that implements “preloading all of its bean definition information,” which is related to BeanDefinition.

  • Just list all the beans in the current container; To get all beans, including the parent BeanFactory, you can do so through the BeanFactoryUtils utility class.

  • Selective enumeration, which ignores any singleton beans registered by other means (such as the registerSingleton method for the ConfigurableBeanFactory);

    The exceptions are getBeanNamesForType and getBeansOfType, which check for such hand-registered singleton beans, and the getBean of the BeanFactory, which also allows transparent access to such special beans.

    • Purpose of selective enumeration:

      The registerSingleton method is defined in the ConfigurableBeanFactory interface. Such as it is called in AbstractApplicationContext interface prepareBeanFactory method, to directly register several internal use SpringFramework components. The SpringFramework doesn’t want developers to manipulate them directly, so it hides them in this way.

  • Most methods are not suitable for frequent calls, with the exception of getBeanDefinitionCount and containsBeanDefinition.

    • Because there are no business requirements that go deep into the bottom of the IOC container, they can be read and cached without frequent calls.

AutowireCapableBeanFactory-*

  • You can support autowiring itself, and you can also make existing beans autowiring. “Existing” actually refers to beans that are not managed by the SpringFramework.

  • Usage Scenarios:

    • This piece AutowireCapableBeanFactory interface Cannot be used in the regular application code. In general, stick with BeanFactory or ListableBeanFactory.

    • When other frameworks integrate with SpringFramework, the integration code of other frameworks can take advantage of this interface if some Bean instances of other frameworks are not controlled by SpringFramework but need to inject objects managed by SpringFramework.

      • The typical scenario is that you write a Servlet that needs to import an existing Service from the IOC container. So you can go with DL or DI. The implementation of DI requires thatAutowireCapableBeanFactoryHelp with the injection.
  • This interface generally use less than, not in the ApplicationContext implementation, but also can through the ApplicationContext getAutowireCapableBeanFactory () method from the application context.

  • You can use BeanFactoryAware injection


ConfigurableBeanFactory

With the “configurable” feature:

  • Readable and writable.ordinaryBeanFactoryOnly get related operations, whileConfigurableAt the beginning ofBeanFactoryorApplicationContextI have the set operation.
  • Most of theBeanFactoryThe implementation class implements the configured interface and can call the methods defined in itBeanFactoryModify, extend, etc.
  • ConfigurableBeanFactoryInterfaces are not expected to be used by developers in application code, but rather insisted uponBeanFactoryListableBeanFactory. becauseThe program should not be correct during executionBeanFactoryMake frequent changes, there should only be read action, not write action.

14.2 BeanFactory implementation class

With the help of IDEA, the implementation classes of BeanFactory can be taken out to form a graph :(of course, not all of them are included in this diagram, only the most core implementation classes are included)

AbstractBeanFactory

  • It is aBeanFactoryThe most basic abstract implementation

    It can get the Bean definition information from the configuration source (XML, LDAP, RDBMS, and so on you saw earlier), and the Bean definition information is the BeanDefinition.

    It provides all the functionality of the ConfigurableBeanFactory SPI. SPI, or Service Provider Interface, is a Service discovery mechanism built into the JDK. That is, it can load classes that are pre-configured in a particular location. See section “Advanced Module Assembly” for details.

  • Support for beans

    Such can provide a single instance of the Bean cache (by its parent class DefaultSingletonBeanRegistry), singleton Bean/prototype decision, alias processing (from AliasRegistry interface), the consolidation of Bean definitions (involves the Bean To inherit, as described in subsequent sections), Bean destruction action support, and so on.

    In addition, it can manage the BeanFactory hierarchy by implementing the HierarchicalBeanFactory interface

  • It defines template methods

    The primary template methods that subclasses implement are getBeanDefinition and createBean, which retrieve bean definition information for a given bean name and create an instance of the bean based on the given bean definition information, respectively. Both of these methods play an important role in the IOC container initialization phase.

    CreateBean is a creation entry for all beans that SpringFramework can manage.


AbstractAutowireCapableBeanFactory-***

AbstractAutowireCapableBeanFactory the most core functionality: Bean creation, fill and rely on automatic injection, Bean initialization.

  • Provides the creation logic implementation of the Bean

    • To achieve theAutowireCapableBeanFactoryInterface, which means it canRealize auto injection/auto assembly of components.
    • inheritedAbstractBeanFactoryAbstract class, and implement thecreateBeanMethod, meaning it hasThe ability to create beans. (but eventually bean creation is defined AbstractAutowireCapableBeanFactory protected methodsdoCreateBean).
  • Automatic injection of attribute assignment and dependency is implemented

  • Some template methods are implemented

    Unlike AbstractBeanFactory, it does not implement all template methods. Instead, it implements the resolveDependency() template method: property dependencies defined in the members of a resolvable Bean for auto-assembly by type.

  • Not responsible for registration of BeanDefinition

    It implements the logic for creating, assigning, injecting, and initializing beans, but it is not responsible for how the Bean definition enters the BeanFactory.


DefaultListableBeanFactory-***

The only landing implementation of the BeanFactory currently in use.

  • Is the final default implementation of BeanFactory, without the abstract identifier. Is the default implementation ConfigurableListableBeanFactory and BeanDefinitionRegistry interface.

  • On the basis of AbstractAutowireCapableBeanFactory, complete the information on registered Bean definitions

    • Registration bean definition information is achieved through the BeanDefinitionRegistry above;
    • The complete BeanFactory management of beans should be: first register the Bean definition information, then complete the Bean creation and initialization action.
  • Not responsible for things like parsing bean definition files

    • BeanFactoryAs a container for unified management of Bean components, its core job isControls the life cycle of beans during the creation phase; Specialized components handle where beans come from, how they are created, and what dependencies are injected (including those mentioned aboveBeanDefinitionReaderIncluding some other components).
  • A simplified version StaticListableBeanFactory, but not commonly used


XmlBeanFactory-*

After SpringFramework 3.1 XmlBeanFactory officially marked as obsolete, instead of the solution is to use DefaultListableBeanFactory + XmlBeanDefinitionReader, This design is more consistent with the single responsibility principle of components.

14.3 Summary and Thinking

  1. What is a BeanFactory? What basic features does BeanFactory implement?

  2. What are the important features of the advanced BeanFactory extension?

  3. Why should BeanFactory’s implementation class define template methods? What is the purpose?

    The SpringFramework makes extensive use of the template method pattern to design core components, with the idea that a parent class provides the logical specification and a subclass provides the implementation of concrete steps.

  4. Who is the final BeanFactory implementation? What are its features?

IOC container description -ApplicationContext

It is recommended to use ApplicationContext rather than BeanFactory. ApplicationContext compares the BeanFactory extension:

Feature BeanFactory ApplicationContext
Bean instantiation and property injection Yes Yes
Life cycle management No Yes
Bean backend processor support No Yes
BeanFactory post-processor support No Yes
Message Transformation Service (internationalization) No Yes
Event publishing mechanism (event driven) No Yes

15.1 Parent and child Interfaces of ApplicationContext

ApplicationContext

ApplicationContext is the core interface that provides configuration for the application. It is read-only while the application is running, but it can be reloaded if supported.

  • ApplicationContext combines multiple functional interfaces:

    • Bean factory methods for accessing application components. Inherited fromListableBeanFactory
    • The ability to load file resources in a common manner. Inherited fromResourceLoaderInterface.
    • Ability to publish events to registered listeners. Inherited fromApplicationEventPublisherInterface.
    • The ability to parse messages, supporting internationalization. Inherited fromMessageSourceInterface.
    • supportParent and child contextHierarchy of description. The context includes containers, as well as dynamic enhancement, resource loading, event listening mechanisms, and many other extensions.
  • Responsible for partial callback injection:

    • In addition to the standard BeanFactory lifecycle features, ApplicationContext implementation will also test and call the ApplicationContextAware bean, ResourceLoaderAware bean, ApplicationEventPublisherAware Bean and MessageSourceAware bean. In turn, beans in Aware are injected into the ApplicationContext.

      • Because ApplicationContext inherits several interfaces from their respective Aware interfaces, for exampleResourceLoaderResourceLoaderAware

ConfigurableApplicationContext

Similar to ConfigurableBeanFactory, ApplicationContext is “writable”.

Configuration and life-cycle related methods are encapsulated in this interface to avoid exposure to the callers of ApplicationContext. The methods of this interface should only be used by start and close code.

Classes that implement this interface can be modified by client code for certain internal configurations: ConfigurableApplicationContext expanded the setParent, setEnvironment, addBeanFactoryPostProcessor addApplicationListener, Are methods that can change the ApplicationContext itself.

EnvironmentCapable

In the SpringFramework, an interface ending in Capable usually means that a specific method of the interface can be passed (usuallygetXXX()) get specific components.

According to this concept, the EnvironmentCapable interface should fetch the Environment through a getEnvironment() method, and it does.

  • All Spring’s ApplicationContext has EnvironmentCapable functionality.

  • It is the interface that gets and exposes the Environment reference. It is primarily used to perform instanceof checks in framework methods that accept instances of the BeanFactory so that they can interact with the environment.

    Environment is a separate abstraction from the SpringFramework, similar to the runtime Environment, which holds the configuration of the application to run.

  • ConfigurableApplicationContext redefined getEnvironment (), and narrowing the scope of the signature, obtain ConfigurableEnvironment

MessageSource

MVC – interpretation

Components that support internationalization. Internationalization refers to the access to different regions and countries, which can provide corresponding pages and data in line with users’ reading habits (languages).

Spring for production provides two existing implementations: ResourceBundleMessageSource, ReloadableResourceBundleMessageSource.

ApplicationEventPublisher

IOC event-driven mechanism – Explanation

Publisher of events. An implementation of the ApplicationContext container as a broadcaster in the observer pattern.

ResourcePatternResolver

The resource file is parsed according to a specific path.

  1. It is an extension of ResourceLoader, which implements basic parsing, and ResourcePatternResolver, which supports path resolution with * in the form of Ant. This mode can be written as follows:

    • /WEB-INF/*.xmlMatch:/WEB-INFAny XML file in the directory
    • /WEB-INF/**/beans-*.xmlMatch:/WEB-INFAny of the following levels of directoriesbeans-XML file at the beginning
    • /**/*.xml: Matches any XML file
  2. ResourcePatternResolver matches not only Webapps files in Web projects, but also classpath files by adding a prefix of classpath*: to the resource path.

15.2 Implementation class of ApplicationContext

AbstractApplicationContext

  1. AbstractApplicationContext is ApplicationContext abstract implementation, is the core of the implementation class, define and implement the most application features and functions of context. These abstract implementations mainly function as specifications (with the help of template methods), and the actual actions need to be implemented by subclasses themselves.

  2. Can handle special types of beans (post-processor, listener).

  3. ApplicationContext interfaces realized internationalization MessageSource ApplicationEventMulticaster, events of radio interface, that as a container, in order to support different types of components into the need, You can think of yourself as a different bean (cast to multiple types) :

    • aMessageSourceIt can also be provided in context as a plain bean named"messageSource"
    • As type isApplicationEventMulticaster"applicationEventMulticaster"Bean to provide.
  4. By default, AbstractApplicationContext loading resource file strategy is directly inherited DefaultResourceLoader strategy, from the classpath to load; But in a Web project, it can be loaded from the ServletContext and needs to override the getResourceByPath() method.

  5. Refresh, a core method that controls the lifecycle of the ApplicationContext, is defined

GenericApplicationContext

  1. Have an internal oneDefaultListableBeanFactoryInstance; To achieve theBeanDefinitionRegistryInterface to which any bean definition reader can be applied.
  2. With the help ofBeanDefinitionRegistryHandle special beans.
  3. GenericApplicationContext could refresh once, because it is initialized in the constructorDefaultListableBeanFactory, while initializing goodBeanFactory It is not allowed to be refreshed repeatedly at run time. – this is different from AbstractRefreshableApplicationContext below.

AbstractRefreshableApplicationContext

  1. Every time I refreshA new internal one will be createdBeanFactoryThe instance(i.e.DefaultListableBeanFactory), which is not created during initialization.
  2. The only method that subclasses need to implement isloadBeanDefinitions, which is called every time you refresh. A concrete implementation should load the bean definition information into a givenDefaultListableBeanFactory, typically delegated to one or more specific bean definition readers.
  3. In a Web environment, there is a similar parent classAbstractRefreshableWebApplicationContext. The refresh strategy is the same as without the Web, with additional extensions to servlet-related parts.AbstractRefreshableWebApplicationContextThere’s one insideServletContextAnd supports Bean injectionServletContextServletConfigComponents in servlets, etc.

AbstractRefreshableConfigApplicationContext

Use to add generic processing for a specified configuration location.

AbstractXmlApplicationContext

  1. Subclasses (ClassPathXmlApplicationContext and FileSystemXmlApplicationContext) only need to implement getConfigLocations and/or getConfigLocations method, To adjust the default read location of the configuration file.

  2. The realization of the loadBeanDefiitions

    @Override protected void loadBeanDefinitions(DefaultListableBeanFactory beanFactory) throws BeansException, IOException {// Create a new XmlBeanDefinitionReader for the given BeanFactory. // Parse XML configuration files with XmlBeanDefinitionReader XmlBeanDefinitionReader beanDefinitionReader = new XmlBeanDefinitionReader(beanFactory); // Configure the bean definition reader with this context's // resource loading environment. beanDefinitionReader.setEnvironment(this.getEnvironment()); beanDefinitionReader.setResourceLoader(this); beanDefinitionReader.setEntityResolver(new ResourceEntityResolver(this)); // Allow a subclass to provide custom initialization of the reader, // Then proceed with actually loading the BeanDefinitionReader. BeanDefinition initBeanDefinitionReader(beanDefinitionReader); loadBeanDefinitions(beanDefinitionReader); }Copy the code

    As you can see, it does not parse the XML configuration file itself; it combines an XmlBeanDefinitionReader and leaves it to parse.

    Call getConfigResources and getConfigLocations, take the path/resource class of the configuration file, and give it to BeanDefinitionReader:

    protected void loadBeanDefinitions(XmlBeanDefinitionReader reader) throws BeansException, IOException { Resource[] configResources = getConfigResources(); if (configResources ! = null) { reader.loadBeanDefinitions(configResources); } String[] configLocations = getConfigLocations(); if (configLocations ! = null) { reader.loadBeanDefinitions(configLocations); }}Copy the code

ClassPathXmlApplicationContext

  1. The configuration file can be loaded using Ant pattern matching (the classic notation is application-*.xml declared in web.xml).

  2. If there are multiple configuration locations, the newer BeanDefinitions will override the BeanDefinitions in the earlier loaded file, which can be used to intentionally override some Beandefinitions through an additional XML file.

    In general, if a Bean is declared in the XML configuration file of a JAR package and the same Bean is declared in the resources directory of the project, the Bean declared in the JAR package will be overwritten, which is the configuration file load priority setting.

  3. Due to the ClassPathXmlApplicationContext inherited AbstractXmlApplicationContext, And AbstractXmlApplicationContext internal combination is actually a XmlBeanDefinitionReader, so there can be a combination of the method of use:

    • usingGenericApplicationContextOr a subclassAnnotationConfigApplicationContext, cooperateXmlBeanDefinitionReaderAnnotation-driven and XML-driven are both available.

AnnotationConfigApplicationContext

  1. Is an annotation-driven IOC container. Inherits itselfGenericApplicationContext, and can only refresh once.
  2. In addition to@ComponentAnd a couple of notes that came out of it, and more importantly@ConfigurationNotes, a by@ConfigurationThe annotated class is equivalent to an XML file.
  3. Initialization is done in two ways: either usingregister(Class ...)One-to-one registration of configuration classes, or usescan(String ...)Perform packet scanning directly.
  4. withClassPathXmlApplicationContextSimilarly, configuration classes are parsed in order. If there are more than one@ConfigurationClass, defined in subsequent classes@BeanMethod overrides the methods defined in the previous class.

15.3 Summary and Thinking

  1. What is theApplicationContext? It has to do withBeanFactoryWhat is the relationship between?
  2. ApplicationContextCompared withBeanFactoryWhat features have been extended?
  3. ApplicationContextBeanFactoryHow are they connected?
  4. Finally landed the realizationApplicationContextWhat are the core features?