"Mastering Spring 4.x" Reading Notes (1)-SpringIoC is enough to read this article

Welfare at the end of the article: Scan the QR code at the end of the article and reply to the keyword "SpringIoC" to get a complete mind map of the summary.

Spring4.x-IoC

IoC basic concepts

IoC (Inverse of Control): The selection control of the interface implementation class is removed from the calling class and transferred to a third party for decision, that is, the Spring container is controlled by Bean configuration.

The concept of IoC is not very intuitive. Later, someone proposed the concept of DI to replace IoC.

DI (Dependency Injection): The dependency of the calling class on the implementation class of an interface is injected by a third party (container or collaboration class) to remove the dependency of the calling class on the implementation class of an interface.

The types of IoC are:

  1. Constructor injection
  2. Attribute injection
  3. Interface injection (effect is similar to attribute injection, not recommended)

Spring supports constructor injection and attribute injection.

IoC implementation-reflection

The Java language allows indirect operation of Class in a programmatic way. After the Class file is loaded by the class loader, a meta-information object describing the Class structure will be formed in the JVM, through which the structural information of the Class can be learned. It opens up a way to manipulate Class objects in a programmatic way. The main classes involved in Java reflection are as follows:

ClassLoader

Class loader: Responsible for finding the bytecode file of the class and constructing the component that the class represents the object in the JVM

Class loading steps:

  1. Loading: Find and import Class files
  2. Link
    ① Verification: Check the correctness of the data loaded into the Class file
    ② Preparation: Allocate storage space for the static variables of the class
    ③ Resolution (optional): Convert symbolic references into direct references
  3. Initialization: Perform initialization work on static variables and static code blocks of the class

JVM run-time generated three ClassLoader: root loader, ExtClassLoader, AppClassLoader
subclass root ClassLoader loader is not, which is written in C ++, responsible for loading the JRE core libraries: rt.jar, charsets.jar and other
ExtClassLoader, AppClassLoader are Subclass of ClassLoader. Ext is responsible for loading the JAR class package in the JRE extension directory ext, and AppClassLoader is responsible for loading the class package under the Classpath path.

The three loaders have a parent-child hierarchical relationship. By default, AppClassLoader is used to load the classes in the application. The JVM is fully responsible for the delegation mechanism when loading classes (/ parent delegation mechanism):

  • The classes that this class depends on and references are also loaded by this ClassLoader (unless you explicitly use other ClassLoaders); (full responsibility)
  • First entrust the parent loader to find the target class, if not found, find and load the target class from its own class path. (Delegation mechanism)

The main method:

  1. defineClass (String name, byte [] b, int off, int len): Convert the byte array of the class file into the java.lang.Class object inside the JVM. The byte array can be obtained from the local file system or remote network. The parameter name is the fully qualified class name corresponding to the byte array. This method is called when the JVM loads the class to construct the Class object
  2. getParent () Get the parent loader of the loader. Except for the root loader, all class loaders have only one parent loader. The parent loader of ExtClassLoader is the root loader, not written in Java language, so it returns null when this method is called;
  3. loadClass (name), loadClass (name, resolve): load classes by fully qualified class names;
  4. findSystemClass (name): load the Class file from the local file system;
  5. findLoadedClass (name): Check if the ClassLoader has loaded a certain class, it will return the Class object if it has been loaded, otherwise it returns null.

The reference relationship between Class files, class loaders, and Class objects is shown in the figure:
Class loading mechanism

The main reflection class

  1. Constructor: The constructor reflection class can be obtained through the getContructor (s) method of the Class object. Its main method is newInstance to create a class object instance, which is equivalent to the new keyword.
  2. Method: The reflection class of the class method, which can be obtained by the getDeclaredMethod (s) method of the Class object. Its main method is invoke to execute this method of the specified object. At the same time, you can obtain the method's return, parameter type, exception, and annotation information through other methods
  3. Field: Class member variable reflection class, which can be obtained through the getDeclaredField (s) method of the Class object. Its main method is to set the value for the specified object field, and the basic type field to set the value through setInt / setBoolean.

Resource access and loading

Spring accesses the configuration file or reads the configuration class to initialize, start, and refresh the container. Resource access is implemented as the underlying foundation of the Spring framework. How is it implemented? What extension methods are provided? Let's take a closer look ...

Spring designed the Resource interface to provide stronger access to the underlying resources for applications. Through the Spring interface, you can place Spring configuration information anywhere, such as databases, LDAP, etc.

Resource plays an indispensable role in the Spring framework. Spring uses Resource to load various resources, including configuration file resources and international property file resources. The specific implementation class is as follows:

Resource implementation class

Resource implementation architecture

  1. WritableResource: The word interface class defines methods related to writable resources, and its implementation classes are FileSystemResource and PathResource.

  2. ClassPathResource: Resources under the class path, the resources are represented by the class path.

  3. UrlResource: encapsulates java.net.URL, and can access the resources represented by the URL, such as file system resources and HTTP resources.

  4. ServletContextResource: A class defined for accessing resources in the context of a Web container. Load resources as the root path of the web application.

  5. ByteArrayResource: The resource represented by the binary array.

  6. InputStreamResource: expressed as an input stream return.

  7. FileSystemResource: File system resource.

  8. PathResource: Represents any resource represented by URL, Path, and system file path.

Resource loading

With the expression method for resources, loading resources needs to be implemented by the resource's path address and resource loader. Resource files can be regarded as materials for processing, and the loader is regarded as a processing processor. Design ideas.

The resource expression
does not need to display and specify the specific Resource implementation class. It is automatically identified by the address. The following addresses and corresponding implementation classes supported:
file: / xxx, http: // xxx, ftp: // xxx use UrlResource to load resources; classpath: / xxx is loaded using ClassPathResource; if there is no prefix, ApplicationContext is used to implement the corresponding type of Resource.

"Classpath:" There is also a "classpath *:" prefix, which means matching in multiple package names, otherwise only the first occurrence of the package name is matched, which is applicable when multiple configuration files need to be loaded for sub-module packaging .

Matching characters supported in Ant style:

  • ?: Match any character in the file name.
  • *: Match any number of characters in the file name.
  • **: Match multiple levels of directories

Resource loader
Resource loader class structure

The ResourceLoader interface only supports expressions with resource type prefixes. ResourcePatternResolver extends the ResourceLoader interface to support Ant-style resource path expressions. PathMatchingResourcePatternResolver is a standard implementation provided by Spring.

Spring container-framework level interface

We usually say that the Spring container is specifically in the Spring framework, referring to the three container-level interfaces of BeanFactory, ApplicationContext, and WebApplicationContext used in the Web environment. When the Spring program is started, the container is also through one of the interfaces. Start work. What exactly do these three interfaces mean, and what are the similarities and differences between them, and what specific implementation classes do they have for us to actually use?

BeanFactory

BeanFactory can be regarded as the internal infrastructure of Spring, which is an abstraction of the container, which defines the basic methods of the Bean factory for internal use by Spring; ApplicationContext provides richer functional support on the basis of BeanFactory, such as internationalization support and Framework event system, etc.

For Spring users, we generally use ApplicationContext instead of the underlying BeanFactory. In order to better understand the Spring framework, we still need to understand the design idea of ​​BeanFactory. The main method defined in BeanFactory is getBean (beanName), get the bean by the bean name, and extend the function of BeanFactory through other interfaces, as follows:

BeanFactory class inheritance system

  1. ListableBeanFactory defines the method to access the basic information in the container: check the number, get the configuration name of a certain type of bean, whether the container contains a certain bean, etc.
  2. HierarchicalBeanFactory parent-child cascade IoC container interface, child container can access the parent container through this interface method, and the parent container can not access the child container. The child container can have a bean with the same id as the parent container. Enhanced the scalability and flexibility of the Spring framework, third parties can add sub-containers programmatically to provide some additional features. For example: In SpringMVC, the presentation layer bean is located in a sub-container, which can access the business layer and the beans that are only able to persist, but in turn cannot be accessed.
  3. ConfigurableBeanFactory is an important interface to enhance customizability. Including: set class loader, attribute editor, container initialization post processor and other methods.
  4. AutowireCapableBeanFactory defines a method for automatically assembling the beans in the container according to a certain rule (name or type matching)
  5. SingletonBeanRegistry allows runtime to register single instance beans with containers
  6. BeanDefinitionRegistry provides a method of manually registering BeanDefinition with the container. (Each node element corresponds to the BeanDefinition object representation in the Spring container)

The common implementation class of BeanFactory is DefaultListableBeanFactory, which uses XmlBeanDefinitionReader to read configuration information and start the container:

public class BeanFactoryTest {

    public static void main(String[] args) {
        ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        Resource resource = resolver.getResource("classpath:com/smart/beanfactory/beans.xml");

        DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
        XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(bf);
        reader.loadBeanDefinitions(resource);

        Car car = bf.getBean("car", Car.class);
        car.introduce();

    }
}

ApplicationContext

ApplicationContext extends from the sub-interface of BeanFactory, and inherits the interfaces related to container events and internationalized message access, with more abundant functions. The specific inheritance system is as follows:
Insert picture description here

  • ApplicationEventPublisher allows the container to publish application context events, including startup and shutdown events. Beans that implement the ApplicationListener event monitoring interface can receive container events and respond to the events. There is an ApplicationEventMulticaster in AbstractApplicationContext, which is responsible for saving all listeners so that the container can notify these event listeners when they generate context events
  • MessageSource provides i18n internationalized message access function for applications
  • The implementation class of ResourcePatternResolver has realized the function similar to PathMatchingResourcePatternResolver, which can load the Spring configuration file through the prefix Ant-style resource file path.
  • LifeCycle start and stop methods are used to control asynchronous processing. ApplicationContext will pass the start / stop information to all the Beans in the container that implement this interface to control JMX and task scheduling.

Implementation class

The main implementation classes of ApplicationContext are ClassPathXmlApplicationContext, FileSystemXmlApplicationContext, AnnotationConfigApplicationContext, GenericGroovyApplicationContext.

AnnotationConfigApplicationContext provides a special implementation class for configuration methods based on class annotations; GenericGroovyApplicationContext is a special implementation class for Groovy DSL configuration

Compare with BeanFactory

  • The BeanFactory does not instantiate the Bean when it is initialized. The target Bean is not instantiated until the first time a Bean is accessed. There is a "first penalty" problem. When the ApplicationContext starts the container, all singleton beans are loaded, so the startup will be Slower, but the benefit is to find potential configuration problems early and improve runtime efficiency;
  • ApplicationContext can automatically identify BeanPostProcessor, InstantAwareBeanPostProcessor, and BeanFactoryPostProcessor (collectively called postprocessors) defined in the configuration file, and automatically register them in the application context, and BeanFactory requires manual method registration.

WebApplicationContext

Specially prepared for Web applications, in addition to prototype and singleton, in addition, three new scopes for Bean: request, session, global session. The class inheritance system is:
WebApplicationContext class inheritance system

Spring's web application context and web container can achieve mutual access:
Spring and Web application context fusion

The initialization method of WebApplicationContext is different from that of BeanFactory and ApplicationContext. It needs to be configured to start on the basis of Web container startup, specifically configuring ContextLoaderServlet or ContextLoaderListener to complete the initialization of the container.

Bean life cycle

After understanding the core interface of the Spring container, continue to discuss the Bean managed by the Spring container, which stages will be completed to complete the initialization, and what is the process of destruction?

Spring initializes Bean through several steps, the specific process is shown in the following figure:
Bean life cycle

① If the container registers the InstantiationAwareBeanPostProcessor interface, then call its postProcessBeforeInstantiation method.
② Call the constructor or factory method of the class to instantiate the bean according to the configuration.
③ Correspond to step ①, call its xxxAfterInstantiation method.
④ Correspond to step ①, before setting the property value, call its xxxPropertyValues ​​method.
⑤ Call the Setter method of Bean to set the Bean property value.
⑥ If the Bean implements the BeanNameAware interface, call its setBeanName method to set the BeanName to the Bean.
⑦ Similar to step ⑥, BeanFactoryAware interface, set BeanFactory.
⑧ If BeanFactory is equipped with BeanPostProcessor implementation class, call postProcessBeforeInitialization method.
⑨ If the Bean implements the InitializingBean interface, then call its afterPropertiesSet method.
⑩ Perform the init-method specified by the node or the method annotated with @PostConstruct.
⑪ Correspond to step ⑧, execute its xxxAfterxxx method.
⑫ Return the bean to the caller, cache the single-instance bean, and the prototype-scoped Bean container no longer manages its life cycle.
⑬ When the container is closed, the destroy method is called for the single-instance bean that implements the DisposableBean interface.
⑭ Call the destroy-method specified by the single-instance node or annotate the @PreDestroy method.

The method marked with ☆ in the picture is called a post-processor, and it is attached to the container-level Bean. The impact is global. At the same time, multiple Beans can also be registered and processed in steps. The Ordered interface needs to be implemented.

Stage division

By process

It can be seen that there are many stages of the Bean's declaration cycle process, which is not easy to understand. The whole process can be divided into several types of stages:

  1. Instantiation and its surroundings: including steps ① to ④, involving two classes-InstantiationAwareBeanPostProcessor and the Bean class to be instantiated, after which a semi-finished Bean to be set attribute value is generated;
  2. Attribute setting, object initialization and its surroundings: including steps ⑤ to ⑪, setting various attribute values ​​(including Bean member variables and BeanName optional, BeanFactory optional), and performing object initialization method
  3. Pre-processing of destroying the bean: including steps ⑬ and ⑭, to carry out the cleaning work before destroying the bean.

By life cycle level
Bean life cycle

  1. Bean's own internal methods: including constructor, attribute setting method, initialization method and destroy-method method.
  2. Bean-level life cycle interface methods: including the methods defined by the BeanNameAware, BeanFactoryAware, InitializingBean, and DisposableBean interfaces. Mainly solve the problem of personalized processing.
  3. Container-level declaration cycle interface methods: including InstantiationAwareBeanPostProcessor, BeanPostProcessor interface methods. Mainly solve the problem of common processing of some Bean in the container. (The post-factory processor method also belongs to the container level and is executed once after the configuration is loaded)

In general, in order to achieve decoupling from the Spring framework, we do not need to pay attention to the Bean-level lifecycle interface and related methods. Using init-method and destroy-method to specify the cleanup actions before initialization and destruction can achieve the same effect as the implementation of the interface. However, BeanPostProcesor is different. It provides the container with an entry point for the subsequent processing of the Bean in the form of a plug-in. At the same time, it does not require the Bean to implement the interface. On this basis, it can uniformly extend the functions of Spring.

The Bean life cycle managed by ApplicationContext is similar to BeanFactory, the difference is that the ApplicationContextAware interface execution of the assembly container context is added, and some post-factory processor methods that are executed when the container is started are implemented by implementing the BeanFactoryPostProcessor interface. The processor has CustomEditorConfigurer, PropertyPlaceholderConfigurer, etc.

Configure Bean

XML Schema configuration

xmls declares the namespace referenced by the document

  • Default namespace
  • standard. . . .
  • customize. . . .
    The definition of the namespace is divided into two steps: the first step specifies the name of the namespace; the second step specifies the location of the Schema document format file of the namespace, separated by spaces or carriage returns and line feeds.
  1. xmls:aop=“http://www.springframework.org/schema/aop”
  2. http://www.springframework.org/schema/aop xxx.xsd

Bean basic configuration

  • id (Optional) can specify multiple names, separated by comma, semicolon, and space, multiple identical ids are not allowed
  • name (Optional) supports special characters, can specify multiple, allow the same name (return the bean declared later when returning the bean)
  • class (When id and name are not specified, the fully qualified class name is used. When there are multiple, the first is the fully qualified class name, the second is the suffix # 1, the third is the suffix # 2, anonymous bean : Provide injection value for outer bean)

Naming: id needs to meet the XML naming convention, name does not limit special characters; id and name can specify multiple names; id is unique in the configuration, name can have the same, getBean returns the bean declared later; try to use id.

Dependency injection

  • Attribute injection
    requires the Bean to provide a default constructor, Setter method, and
    JavaBean's special specification for attribute naming: the first two letters of the variable are all uppercase or all lowercase.
  • Constructor injection
    Match parameters by type Match parameters
    by index
    Use type and index match parameters by
    type Self-reflect match parameters by type
    Cyclic dependency problem
  • Factory method injection
    Non-static factory method: factory-bean factory-method, you need to declare the factory class Bean
    static factory method: class attribute specifies the factory class, factory-method specifies the factory method.

Choice of injection method?
Construction method

  • It can ensure that some important attributes are set when the Bean is instantiated, to avoid the situation of useless Beans because some important attributes are not provided.
  • There is no need to provide Setter methods for each property, reducing the number of class methods
  • Better encapsulation of class variables, no need to provide Setter methods to avoid wrong calls

Attribute injection

  • Numerous attributes, long construction signature, poor readability
  • The construction method is not flexible enough, and null must be passed when the attribute is optional
  • When configuring multiple constructors, the problem of matching ambiguity needs to be considered, and the configuration is relatively complicated
  • The construction method is not conducive to the inheritance and expansion of the class, the subclass needs to refer to the complex construction method of the parent class
  • Constructor injection sometimes causes circular dependency problems.

Injection parameters

  1. Literal value
    Basic data type, character string (customizable editor), property tag and value subtag
  2. Reference other bean
    property tags and ref child tags, ref tag beans specify beans, and parent attributes refer to beans in the parent container
  3. Internal bean
  4. null value
  5. Cascading properties
  6. Collection types
    List, Set, Map, Properties, strongly typed collections, and merged collections through parent and child beans

Simplified configuration

  • Literal attribute property / constructor-arg / map-entry value
  • Reference object properties
  • Use the p namespace to
    define collection-type beans, use the util namespace

Autowire

  • byName
  • byType
  • constructor
  • autodetect

Method injection

  • Lookup method injection
    Get a prototype through a singleton bean
  • Method replacement
    MethodReplacer interface

Bean relationship

  • inherit
  • rely
  • Quote

Bean scope

  1. singleton
  2. prototype
  3. Web application environment
  • request
  • session
  • global session

Use notes

  • @Autowired (required)
    annotation attribute
    annotation method
    collection class annotation
  • @Qualifier specifies the name
  • @Lazy
  • Support standard annotations: @Resource and @Inject
    Resource are injected into Beans by name matching, the default is to inject
    Inject by variable name or method name by type, but there is no required attribute
  • @scope
  • @PostConstruct and @PreDestroy (can be multiple)

Java-based configuration

@Configuration
@Bean

Mixed configuration

  • xml refers to the Java class configuration and is implemented through context: component-scan
  • Java class configuration references xml, through @ImportResource

Spring container working mechanism

When discussing the Bean life cycle, many interfaces and components of the Spring container are involved. When were these instantiated? What steps did the Spring container go through when it started? How does the initialization process of the bean and the container startup process connect? These problems are glimpsed from the refresh method of AbstractApplicationContext.

Spring container working mechanism

The above diagram sorts out the various stages that the Spring container goes through. From the configuration file nodes to the complete Bean instance in the container, it can be divided into the following major stages:

  1. The configuration file is processed and the output is the finished BeanDefinition component registered in BeanDefinitionRegistry;
  2. Register special beans, based on BeanDefinition, can identify some special beans, including post-processor, internationalization, event monitoring related beans, etc .;
  3. Initialize all single-instance beans except Lazy tags;
  4. Post a context refresh event.

"Proficient in Spring 4.x" book has detailed introduction to BeanDefinition, property editor, factory post-processor, InstantiationStrategy, BeanWapper and other components. After a brief combing in the figure, you can find a book to read if you are interested.

summary

This article summarizes all aspects of SpringIoC based on "Mastering Spring4.x Enterprise Application Development", starting from the basic concept of IoC, introducing the underlying Java basic technology of SpringIoC, namely reflection, introducing the configuration of Bean and the working mechanism of Spring container and Bean life cycle stage, I hope to help readers understand Spring container, Bean related configuration, internal working mechanism.

Scan the QR code at the end of the article and reply to the keyword "SpringIoC" to get a complete mind map of the summary:
My public account

Published 159 original articles · praised 225 · 210,000 views

Guess you like

Origin blog.csdn.net/lyg673770712/article/details/105641619