Java learning record Spring core loC

Spring IoC container

Ioc Inversion of Control is not a technology, but a design idea

In the development of Ioc, there is no need to create its own instance object, but a Spring Ioc container. The Spring container is responsible for controlling the relationship between programs, rather than being directly controlled by the code. Therefore, the control is taken over by the Spring container, and the control is reversed, which is the design idea of Ioc

Spring provides two IoC containers, BeanFactory and ApplicationContext

BeanFactory

Bean factory is a factory that manages beans. It manages beans according to the definitions in the xml configuration file. It is mainly responsible for initializing various beans and calling their life cycle methods

Load the xml configuration file as follows: (the xml file must be an absolute path)

BeanFactory beanFactory = new XmlBeanFactory(new FileSystemResource("D:\applicationContext.xml"));

ApplicationContext

ApplicationContext is the sub interface of BeanFactory and also the application context. All functions of BeanFactory also add good support for i18n (internationalization), resource access, event propagation, etc

The ApplicationContext interface has two commonly used implementation classes

ClassPathXmlApplicationContext

This class looks for the specified xml configuration file from the ClassPath classpath, finds the specified xml file, and loads the instantiation work, as shown below

ApplicationContext applicationContext = new ClassPathXmlApplicationContext(Spring match
 Set the name of the file);

FileSystemXmlApplicationContext

This class looks for the specified xml configuration file from the file with the specified system path, finds the specified xml file, and loads the instantiation, as shown below

ApplicationContext applicationContext = new FileSystemXmlApplicationContext(Spring match
 Set the path and name of the file);

When reading the configuration file of Spring, FileSystemXmlApplicationContext specifies the location of the configuration file through parameters, which can obtain resources outside the classpath

Bean tag

The root element of the XML format configuration file is < beans >, which contains multiple < Bean > sub elements. Each < Bean > sub element defines a Bean and describes how the Bean is assembled into the Spring container.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.2.xsd">

    <!-- use id Attribute definition person1,The corresponding implementation class is com.mengma.person1 (Class path and package path)-->
    <bean id="person1" class="com.mengma.person1 " />
    <!--use name Attribute definition person2,The corresponding implementation class is com.mengma.domain.Person2 (Class path and package path) -->
    <bean name="Person2" class="com.mengma.domain.Person2"/>
        
</beans>

bean properties

Attribute namedescribe
idIs the unique identifier of a Bean. The Spring container configures and manages the Bean through this attribute
nameThe Spring container can also configure and manage beans in the container through this attribute. Multiple names can be specified for beans in the name attribute, and each name is separated by a comma or semicolon
classThis attribute specifies the specific implementation class of the Bean. It must be a complete class name, using the fully qualified name of the class
scopeIt is used to set the scope of the Bean instance. Its attribute values include singleton, prototype, request, session and global Session. Its default value is singleton
lazy-initDelay loading (true/false, default false). It takes effect only when the object is obtained through the getbean() method
init-methodInitialize object method
destroy-methodDestroy object method
listDependency injection used to encapsulate List or array types
setDependency injection used to encapsulate Set type properties
mapDependency injection used to encapsulate Map type attributes

Instance Bean

There are three ways to instantiate an instance Bean: constructor instantiation, static factory instantiation, and instance factory instantiation

  1. Create a solid object

    Project src directory com People

    package com;
    
    public class People {
        int id;
        String name;
        
        public People() {
            System.out.println("Parameterless instance");
        }
        public People(int id , String name) {
            System.out.println("Parametric instance");
            this.id = id;
            this.name = name;
        }
        
        @Override
        public String toString() {
            return "People{" +
                    "id=" + id +
                    ", name='" + name + '\'' +
                    '}';
        }
    }
    
    
  2. Create factory
    Project src directory com MyFactory

    package com;
    
    public class MyFactory {
        
        public MyFactory() {
            System.out.println("MyFactory--Structure!");
        }
        
        /**
         * Example method
         */
        public People instanceFun(){
            System.out.println("MyFactory---instanceFun");
            return new People(001,"Jackie Chan");
        }
        
        /**
         * Static method
         */
        public static People staticFun(){
            System.out.println("MyFactory---staticFun");
            return new People(002, "Bruce Lee");
        }
        
    }
    
  3. Create Spring configuration file
    If it is a Maven project, put it under resources; If not, customize the location

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
    
    <!--    Default construction-->
        <bean id="test01" class="com.People" lazy-init="true"/>
    <!--    Parametric structure-->
        <bean id="test02" class="com.People" lazy-init="true">
            <constructor-arg name="id" value="001"/>
            <constructor-arg name="name" value="Hey, hey, hey"/>
        </bean>
        <bean id="test03" class="com.People" lazy-init="true">
            <constructor-arg index="0" value="002"/>
            <constructor-arg index="1" value="La La La"/>
        </bean>
    <!--    Factory method-->
        <bean id="test04" class="com.MyFactory" lazy-init="true"/>
        <bean id="test05" factory-bean="test04" factory-method="instanceFun" lazy-init="true"/>
    <!--    Factory method (static)-->
        <bean id="test06" class="com.MyFactory" factory-method="staticFun" lazy-init="true"/>
    </beans>
    
  4. Create test class
    Prerequisite: dependency needs to be introduced

    package com;
    
    import org.junit.Test;
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.support.ClassPathXmlApplicationContext;
    
    public class MyTest {
        
        String createType = "createType.xml";
        
        @Test
        public void test01(){
            ApplicationContext applicationContext = new ClassPathXmlApplicationContext(createType);
            People test01 = (People) applicationContext.getBean("test01");
            People test02 = (People) applicationContext.getBean("test02");
            People test03 = (People) applicationContext.getBean("test03");
            People test05 = (People) applicationContext.getBean("test05");
            People test06 = (People) applicationContext.getBean("test06");
            System.out.println("============");
            System.out.println("test01 : " + test01);
            System.out.println("test02 : " + test02);
            System.out.println("test03 : " + test03);
            System.out.println("test05 : " + test05);
            System.out.println("test06 : " + test06);
        }
        
    }
    
  5. Result view
    Test runs using JUnit

    Parameterless instance
     Parametric instance
     Parametric instance
    MyFactory--Structure!
    MyFactory---instanceFun
     Parametric instance
    MyFactory---staticFun
     Parametric instance
    ============
    test01 : People{id=0, name='null'}
    test02 : People{id=1, name='Hey, hey, hey'}
    test03 : People{id=2, name='La La La'}
    test05 : People{id=1, name='Jackie Chan'}
    test06 : People{id=2, name='Bruce Lee'}
    

Dependency injection DI

DI - Dependency Injection, i.e. "Dependency Injection". The resources required by the target can be specified through simple configuration without any code

IOC and DI are different descriptions of the same concept. IOC is an idea; DI is the means to realize it. The Spring framework uses dependency injection to implement IOC

Child element name and attributeParent element nameexplain
constructor-argbeanYou can use this element to pass in construction parameters for instantiation. The index attribute of the element specifies the sequence number of the construction parameter (starting from 0), and the type attribute specifies the type of the construction parameter
propertybeanIt is used to call the Set method in the Bean instance to complete attribute assignment, so as to complete dependency injection. The name attribute of this element specifies the corresponding attribute name in the Bean instance
entrymapUsed to set a key value pair. The key attribute specifies the key value of string type, and the ref or value child element specifies its value
attributevalueexplain
refproperty,constructor-arg,...The bean attribute in this element is used to specify a reference to a bean instance in the bean factory
valueproperty,constructor-arg,...Used to specify a constant value directly
autowirebyName/byTypeAutomatic assembly according to Property feature name or Type

Injection classification

set injection

Pass in the instance of the callee through the set method. This injection method is simple and intuitive, so it is widely used in Spring dependency injection

public class TeamService {
    
    //Injection test
    private TeamDao teamDao;
    
   ···
    
    //set injection (implement TeamDao object instance)
    public void setTeamDao(TeamDao teamDao) {
        this.teamDao = teamDao;
    }
    ···
}

Constructor Injection

While constructing the caller instance, complete the instantiation of the callee. Setting dependencies using constructors

public class TeamService {
    
    //Injection test
    private TeamDao teamDao;
    
    public TeamService() {}
    //Constructor Injection 
    public TeamService(TeamDao teamDao) {
        this.teamDao = teamDao;
    }
    ···
}

Automatic injection

You can set the autowire property value through the bean tag to perform implicit automatic injection for the reference type property (the default is not to automatically inject the reference type property). According to the different judgment criteria of automatic injection. It can be divided into two types:

byName: automatically inject by name
byType: automatically inject according to the type

byName

Prerequisite: the bean tag attribute id and name values in the xml configuration file are the same as the attribute name in the caller class, and the dependent instance can be automatically injected by byName

. xml configuration file:

	<!--id Property value specifies the name-->
	<bean id="teamDao" class="com.dao.TeamDao"/>
<!--    Automatic injection-->
    <!--with Name Injection criteria-->
    <bean id="teamService" class="com.service.TeamService" autowire="byName"/>

Caller TeamService class:

public class TeamService {
    
    //Injection test (same attribute name teamDao)
    private TeamDao teamDao;
    
    ···
}

byType

Prerequisite: the class specified by the class value attribute of the bean tag attribute in the xml configuration file is the same as the attribute type in the caller class. You can use byType to automatically inject dependent instances

. xml configuration file:

	<!--class Property value specifies the class-->
	<bean id="teamDao" class="com.dao.TeamDao"/>
<!--    Automatic injection-->
    <!--with Name Injection criteria-->
    <bean id="teamService" class="com.service.TeamService" autowire="byType"/>

Caller TeamService class:

public class TeamService {
    
    //Injection test (same attribute type TeamDao)
    private TeamDao teamDao;
    
    ···
}

Annotation assembly Bean

In Spring, although the assembly of beans can be realized by using XML configuration files, if there are a large number of beans in the application, the XML configuration files will be too bloated, which will bring some difficulties to maintenance and upgrade. Therefore, Spring provides annotation applications, and some changes need to be made on the basis of the original operation environment, so as to reduce too many beans

@Component

Add the @ Component annotation on the class to indicate that the permission of the object of the class instance is handed over to the Spring container. The annotated value attribute is used to specify the id value or name value of the bean, but generally, the value attribute can be omitted! (the annotation specifies that the id is the initial lowercase of the class name)

The following annotation has the same usage and function as @ Component annotation, but different meanings!

  • @Repository
    Annotation of dao layer implementation class (persistence layer)
  • @Service
    Annotation of service layer implementation class (business layer)
  • @Controller
    Annotation of controller layer implementation class (control layer)

@Value

This annotation injects a value for the specified attribute. This annotation is used on a property of a class or on a specified set method.
The annotation injection principle is the same as that of the set method, so the set method can also be used

package com;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class MyUser {
    //Mode 1
    @Value("001")
    private int id;
    @Value("Zhang San")
    private String name;
    @Value("23")
    private int age;
    @Value("Los Angeles")
    private String locateion;
    
    ···
    
    //Mode 2
    @Value("001")
    public void setId(int id) {
        this.id = id;
    }
    @Value("Zhang San")
    public void setName(String name) {
        this.name = name;
    }
    @Value("23")
    public void setAge(int age) {
        this.age = age;
    }
    @Value("Los Angeles")
    public void setLocateion(String locateion) {
        this.locateion = locateion;
    }
    
   	···
}

Packet scanning

The component scanner needs to be configured in the xml configuration file to scan the annotations in the specified package. If no scan is added, the annotation added by the object cannot be instantiated

xml configuration file add scan

  1. beans tab configuration properties
    xmlns:context attribute: xmlns:context=“ http://www.springframework.org/schema/context "
    xsi:schemaLocation attribute (add value):
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context.xsd

    ···
    <beans xmlns="http://www.springframework.org/schema/beans"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xmlns:context="http://www.springframework.org/schema/context"
           xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans.xsd
           http://www.springframework.org/schema/context
           http://www.springframework.org/schema/context/spring-context.xsd">
    	···
    </beans>
    
  2. Context: the component scan tag specifies the package scan
    Separators can use commas (,) semicolons (;) You can also use spaces. Spaces are not recommended.

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns:context="http://www.springframework.org/schema/context"
        xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd">
    <!--    Packet scanning method 1: (Package path Annotation.dao,Annotation.service,Annotation.controller)-->
    	    <context:component-scan base-package="Annotation.dao"/>
    	    <context:component-scan base-package="Annotation.service"/>
    	    <context:component-scan base-package="Annotation.controller"/>
    <!--    Packet scanning method 2: (Package path Annotation.dao,Annotation.service,Annotation.controller)-->
    	    <context:component-scan base-package="Annotation.dao;Annotation.service;Annotation.dao"/>
    </beans>
    
  3. Add the corresponding annotation

Automatic injection

To automatically inject a specified object, you need to add annotations to the object, and the parent package or specified class has been scanned!

@Autowired

It is used to label the attribute variables, attribute Set method and construction method of the Bean (the premise of the application of construction method, and the parameters must specify the corresponding instance object), and cooperate with the corresponding annotation processor to complete the automatic configuration of the Bean. By default, the Bean is assembled according to its type

@Autowired also has an attribute required, and the default value is true, indicating that the program will be terminated after matching fails; If the value is false, the property value will be null after matching failure

@Qualifier

When used with the @ Autowired annotation, the default assembly by Bean type will be modified to assembly by Bean instance formation name, and the Bean instance name is specified by the value parameter of the @ Qualifier annotation

@Resource

This annotation is in jdk1 Version 6 or above supports use. Bean attribute can specify automatic injection according to type or name, and can be used in attribute variable and attribute Set method

Keywords: Java Spring ioc

Added by jammer on Sun, 23 Jan 2022 15:48:57 +0200