Spring-beans Architecture Design Principle __spring

Source: Internet
Author: User
Tags aop class definition
IOC

IOC, the official definition is to rely on injection (Dependency injection) or control reversal (inversion). It's hard to understand the literal. But any mode is from people's behavior thinking way, as long as the imagination of the day-to-day production process, before the production is the customer orders, the list will specify the required products, including the product specifications of the attributes, and then the factory production.

IOC is a similar process in which the IOC produces what the user claims to be. In the process, the user simply gives a list of requirements without having to bother to new and constantly setting various properties. Spring IOC

Spring-beans is the IOC's most famous realization, and has not been one, and is now almost synonymous with the IOC. Although more people tend to think that beans is just a factory, the context is the container, but the context itself is more like the appearance of beans-driven by it beans, and the ability to combine beans internally, and the context itself is based on beans. The bottom and most solid foundation of spring is beans, which is the cornerstone component of spring, and all of the spring components we know are based on it. Spring-beans Overall Architecture

Spring-beans's excellent scalability enables spring to be almost all-inclusive, with users simply following spring Beans's relevant specification--spring.schema defines the grammar specification for the configuration document, Spring.handler the parsing tool that defines the customized configuration--you can plug the bean into the spring container. After the bean is plugged in, you can even replace the bean by implementing Beanpostprocessor or Init-method to the bean after processing.

Spring-beans's excellent design makes spring more and more like an eco-circle, with powerful components such as BEANS,AOP, context, MVC, annotation, and so on, in addition to some excellent third-party components such as Dubbo.

Take AOP, for example, to generate advised Beans (Advisor) for AOP configuration in the parse phase, then get advised beans at the post-processing stage of all beans, and determine whether to adapt to the current bean through the filter. If applicable, the bean is woven into the advice. If you have time later, you will specialize in AOP, where you don't go further.

Dubbo and AOP are slightly different, the Dubbo extension chooses the Afterpropertiesset in Init method, all strictly Dubbo cannot go to spring, although the Dubbo statement is OK, but in fact it is not suitable for spring features, Instead of going to the spring Jar,dubbo Bean generates ref in the init phase, which is also a proxy-encapsulates the details of remote access. Bean Definition

The core entities of Spring-beans are beandefinition and beanfactory. The former maps our definition, while the latter is the factory where the bean is produced by definition.

The above illustration is a static structure diagram of spring beans, more focused on bean parsing, because 1. Understanding Bean parsing also understands half of spring's scalability; 2. The complexity of beanfactory is not in the organizational structure between classes, but in the complex call links, and there is no need for static structure to do too much description. It should be noted that this is only a conceptual model, not fully mapped to the class, because the abstract level of spring is too high, a concept of entity functions are often coordinated by a number of classes, painting more laborious, similar to beanfactory, the light to understand the relationship between the beanfactory to get headaches, So as far as possible from the conceptual level of description. Important Entity Description Defaultlistablebeanfactory is the default implementation of Beandefintionregistry, which is an adapter that matches beanfactory and Beandefintionregistry, and the factory and definition are unified through it. It is initialized by ApplicationContext and is used as the registry of Beandefinitionreader. Reader load resolution on configuration document, generate definition and register to registry--is actually defaultlistablebeanfactory, so that the factory has the class definition, the bean initialization can also be easily obtained through the internal method of definition. Namespacehandlerresolver is used to get the configuration resolution entity--namespacehandler. Both it and registry are clustered in the context entity--readercontext, in which the parser context can indirectly access handler and registry to obtain the ability to parse and register.

Several other entities are more intuitive and easy to understand, no longer one by one repeat. Overall interaction Process

Beandefinitionreader is the aggregate root that the entire bean resolves, created by ApplicationContext, and passed Defaultlistablebeanfactory as registry to it.

Beandefinitionreader creates a document read entity--docuemntreader is used to load parsing and creates a context--readercontext pass to the document reading entity when STEP3 loads the document. The context runs throughout the parsing process and is passed into the parser when the document reading entity uses parser parsing.

Parse process is the core of the entire loading process, the default parser through the indirect association of the recognizer can be based on different configuration nodes parser switch, when read to Non-default configuration, then switch to the corresponding client parser resolution. After parsing is done, it is registered through the indirectly associated registry, so that the configuration definition enters spring management and is used for Getbean. Client Configuration node resolution

The custom configuration is a very important extension point for spring, and half of spring's powerful scalability is attributed to it, and 80% of the other half is the famous beanpostprocessor that is to be described later. Not only are some third-party extensions (such as the Dubbo mentioned at the beginning) based on it, many of the modules of spring itself are based on it, such as Spring-aop,spring-context, and so on, and the rest of the spring system is based on it, except for the default beans namespaces.

Namespacehandlerresolver is initialized by Beandefinitionreader, which reads the spring.handlers file the first time it is accessed. handlers file definition namespace The mapping relationship between the URI and the corresponding processing class. For example:

Http\://www.springframework.org/schema/context=org.springframework.context.config.contextnamespacehandler

The above line of configuration is the parsing class for the configuration declaration.

Namespacehandlerresolver obtains namespacehandler based on node namespace, and then uses handler to process the custom configuration node.

Public interface Namespacehandler {
    void init ();

    Beandefinition Parse (element element, ParserContext ParserContext);

    Beandefinitionholder Decorate (Node source, beandefinitionholder definition, ParserContext parsercontext);

}

The Init method registers LocalName with a custom parser relationship, and the relationship between parser and LocalName is registered by the handler provider itself. For example:

The public void init () {
        //in 2.0 XSD as as-in 2.1 xsd.
        Registerbeandefinitionparser ("config", new Configbeandefinitionparser ());
        Registerbeandefinitionparser ("Aspectj-autoproxy", New Aspectjautoproxybeandefinitionparser ());
        Registerbeandefinitiondecorator ("Scoped-proxy", New Scopedproxybeandefinitiondecorator ());

        Only in 2.0 xsd:moved to context namespace
        as of 2.1 registerbeandefinitionparser ("spring-configured", New SPRINGC Onfiguredbeandefinitionparser ());
    }

This is the code snippet for the AOP registration parser. Config,aspectj-autoproxy these are the different localname in the Localname,parse process will switch to different parser parsing.

Spring first navigates through the namespace to Handler,handler processing and then parses the current node based on the localname corresponding parser. For example, this configuration, AOP is a namespace, Aspectj-autoproxy is localname. In the whole reading parsing process, we find aopnamespacehandler through AOP, and then use Aspectjautoproxybeandefinitionparser to parse the Aspectj-autoproxy node. To study spring source, be sure to find the corresponding parser, knowing that each configuration item corresponds to the RUN-TIME bean structure to better understand spring, and that parser may generate some default beanpostprocessor if they are not aware of these post processor , then the reading of the code will fragment, into a completely incomprehensible situation. For example, SPRING-AOP is generated by the parser default generation Aopautoproxycreator This beanpostprocessor, after the bean initialization by this processor to the bean generation agent. Bean Fetch


The diagram above is the Getbean process, the whole process is very concise, the actual depth of the code will find very cumbersome.

Beanfactory and Beandefinitionregistry are unified in spring, see the first section, which, for ease of understanding, is split into two conceptual entities.

Note that steps 4th and 6th, the parent attribute can be specified when the bean is configured, and if there is a parent, then the Beanfactory will merge,merge the local and parent by overwriting the parent. It can also be understood as the inheritance of parent. This is exactly the same concept as the parent Bean factory and must be distinguished.

In the beans entity static structure, the parent bean definition and the parent Bean Factory are noted separately. Both are connected, not inherited. The latter is somewhat like the JVM's parent-delegate model, with parent and child having their own context, similar to the JVM's namespace. The parent bean Factory is set by ApplicationContext and cannot be configured. Spring MVC, for example, is two parent-child two containers, and the corresponding beanfactory of the parent container is set to the parentbeanfactory of the child container beanfactory when the container is refresh. Spring Bean State


The bean primarily passes through instantiate,populate,initializebean and REGISTERDISPOSABLEBEAN4 states, and many of the extension interfaces of spring reservations are invoked in the state flow.

Awaremethod
If the bean inherits Beanfactoryaware,beannameaware,beanclassloaderaware, the Initialize phase will beanfactory, beanname, and Bean ClassLoader is set to the bean.
Note that it is not the same as the Applicationcontextaware, which is handled by Beanpostprocessor after set.

Init method
Init method includes not only the configured Init-method methods, but also the Initializedbean Afterpropertiesset callback interfaces, which are both parameterless and can be substituted for each other. In both, the Afterpropertiesset call is in the front. Beanpostprocessor

As mentioned above, the extension capabilities of spring's other half are provided by Beanpostprocessor. First look at its interface definition

Public interface Beanpostprocessor {
    object Postprocessbeforeinitialization (Object bean, String beanname) throws beansexception;

    Object Postprocessafterinitialization (Object bean, String beanname) throws beansexception;
}

Two methods before and after the Init-method call, do the processing of the bean after each. The special attention is postprocessafterinitialization, and most of the spring extensions are done by it, for example, the AOP mentioned above is the process of processing the bean after the generation agent. The corresponding can also use postprocessbeforeinitialization, but at this time Init-method did not execute, after processing need to ensure the impact of Init-method, @PostConstruct method of implementation is at this stage. materialized post processor

Instantiationawarebeanpostprocessor inherits Beanpostprocessor, primarily for processing before and after the bean instantiation.

public Interface Instantiationawarebeanpostprocessor extends Beanpostprocessor {Object postprocessbeforeinstantiation (

    Class<?> Beanclass, String beanname) throws beansexception;

    Boolean postprocessafterinstantiation (Object bean, String beanname) throws beansexception; Propertyvalues postprocesspropertyvalues (propertyvalues PVs, propertydescriptor[] pds, Object Bean, String be
Anname) throws Beansexception; }
Before instantiating, the parameter of this method is Beanclass and Beanname, called before the Bean is instantiated, if the return value of this method is not empty then Getbean end, the user receives the return value of this method. This extension point is primarily reserved for preprocessing, where the user can directly generate a bean of the same type, replacing the actual bean, at which point the actual bean will not be instantiated. After instantiation processing, along with property reprocessing, is a very important extension point within Spring, annotation field injection is done in both phases. There are two key implementations: Commonannotationbeanpostprocessor, which is used for attribute injection in the instantiated post processing phase, mainly for @resource autowiredannotationbeanpostprocessor , this class does property injection in the property post processing phase, mainly for @autowired the former also inherits the Initdestroyannotationbeanpostprocessor class, The class will call the @postconstruct method before Init-method is executed.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.