Introduction to Spring [personal notes]

I Spring concept

Spring is a lightweight J2EE framework, which can solve the complexity of enterprise application development.

Spring has two core parts, IOC and AOP.

(1) IOC: control reversal. Leave the process of creating objects to Spring for management.

(2) AOP: facet oriented. Function enhancement without modifying the source code.

Spring features:

(1) Convenient decoupling and simplified development.

(2) Aop programming support.

(3) Facilitate program testing.

(4) Facilitate integration with other frameworks.

(5) Convenient for practical operation.

(6) Reduce the difficulty of using JAVA EE API.

1.1 INTRODUCTION cases

① Download entry project code

[the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-lwVGQMgy-1642959089932)(X:\Users\Administrator\Desktop\assets\image-20220105140643155.png)]

② Create JAVA project with IDEA

[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-CgHcxYmx-1642959089934)(X:\Users\Administrator\Desktop\assets\image-20220105141428668.png)]

[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-03KhVc4R-1642959089935)(X:\Users\Administrator\Desktop\assets\image-20220105142121783.png)]

③ Introduce related dependencies. Import spring 5 related jar packages

[the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-zxVUERhb-1642959089936)(X:\Users\Administrator\Desktop\assets\image-20220105142406721.png)]

IOC corresponding to Beans and Core

Context corresponds to the context

Expression corresponding expression

Find the corresponding jar package in libs

[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-QnWXz9Ij-1642959089937)(X:\Users\Administrator\Desktop\assets\image-20220105142700818.png)]

There is also a Commons - logging - 1.1.1 jar

Copy to the lib folder of the project, and then import the related dependencies.

File -- > project structure -- > modules -- > dependencies -- > click the plus sign -- > jar to directories

[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-GfGVwVQP-1642959089938)(X:\Users\Administrator\Desktop\assets\image-20220105143352912.png)]

④ Create a common class and create a common method in this class

[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-is2xg2NO-1642959089940)(X:\Users\Administrator\Desktop\assets\image-20220105143922932.png)]

⑤ Create a Spring configuration file and configure the created objects in the configuration file

(1) The Spring configuration file uses xml format

Create an XML file in the src folder, named bean1 xml

Enter the following code in the xml file:

<!-- to configure User Class object creation-->
<bean id="user" class="com.atguigu.spring5.User"></bean>

⑥ Test code writing

Create a test package under the src path for testing.

Create a new test class testspring5 Java, write the test code

package com.atguigu.spring5.testdemo;

import com.atguigu.spring5.User;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class TestSpring5 {
    // The Test package didn't start. The shortcut key alt+enter was used to import
    @Test
    public void testAdd(){
        // 1. Load configuration file (xml)
        ApplicationContext context =
                new ClassPathXmlApplicationContext("bean1.xml");
        // 2. Get the object created by configuration
        // The following sentence is user = context getBean("user",User.class). VaR to create a user object, and alt+enter to import the user class
        User user = context.getBean("user", User.class);

        System.out.println(user);
        user.add();
    }
}

⑦ Run test code

[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-G3MIpzdN-1642959089942)(X:\Users\Administrator\Desktop\assets\image-20220105150042117.png)]

It can be seen that the object created by Spring configuration is successfully obtained

II IOC container

2.1 IOC underlying principle

What is IOC?

IOC is also called control inversion, which means that Spring manages the process of object creation and invocation between objects, so as to reduce the degree of coupling. The above entry case is a simple implementation of IOC.

IOC underlying principle

① XML parsing, factory schema, reflection

In the original way, the common way to call another class in one class is this:

class UserService(){                       		 class UserDao(){
	execute(){										add(){
		UserDao dao = new UserDao();						............
		dao.add();				
	}												}
}												 }

Although this method can intuitively see the calling relationship between objects, it has a fatal disadvantage, that is, the coupling degree of code is too high. If UserDao's method changes, UserService must also change.

To reduce the coupling degree of code, the factory mode is proposed.

class UserService(){                       		 class UserDao(){
	execute(){										add(){
		UserDao dao = UserFactory.getDao();				  ............
		dao.add();				
	}												}
}												 }

//New factory class
class UserFactory(){
    public static UserDao getDao(){
        return new UserDao();
    }
}

Through a factory class, complete the operation of understanding coupling. Reduced UserService and UserDao Coupling between.

Although this method can reduce the coupling degree between UserService and UserDao, the coupling degree of UserFactory is improved, and we finally need to minimize the coupling degree (it is impossible to have no coupling degree at all).

How to further reduce the coupling? The concept of IOC is introduced. [XML parsing, factory schema, reflection]

XML parsing.

The bytecode file of the class is obtained through reflection, and then the content of the class is manipulated. Get the content of class - > class.

IOC process

Step 1: configure the created object with the xml configuration file.

<bean id="dao" class="com.atguigu.UserDao"></bean>

Step 2: there are service class and dao class

class UserFactory{
	public static UserDao getDao(){
		//1.xml parsing
		String classValue = class Attribute value;//Here is the completion of xml parsing
		//2. Create objects by reflection
		Class clazz = Class.forName(classValue);
		return (UserDao)clazz.newInstance();
	}
}
//The advantage of this is that even if the properties of the object are modified, you only need to modify the xml configuration file without moving the userFactory. To further reduce the coupling degree.

2.2 IOC interface (BeanFactory)

  1. The IOC idea is based on the IOC container, and the bottom layer of the IOC container is the object factory.

  2. Spring provides two implementations of IOC containers.

    (1) BeanFactory (the basic implementation of IOC container and the internal interface of Spring, which is generally not used in development)

    // 1. Load configuration file (xml)
            BeanFactory context =
                    new ClassPathXmlApplicationContext("bean1.xml");
            // 2. Get the object created by configuration
            User user = context.getBean("user", User.class);
    

    (2) ApplicationContext (a sub interface of BeanFactory, which provides more and more powerful functions for developers)

    // 1. Load configuration file (xml)
            ApplicationContext context =
                    new ClassPathXmlApplicationContext("bean1.xml");
            // 2. Get the object created by configuration
            User user = context.getBean("user", User.class);
    

    common ground:

    The functions of the two interfaces are similar. Can load the configuration file and then obtain the object created by the configuration.

    difference:

    BeanFactory does not create objects when loading the configuration file, but only when acquiring or using objects.

    The object is created when the ApplicationContext loads the configuration file.

    In development, objects are usually created when the server starts, rather than when they need to be used.

  3. The ApplicationContext interface has implementation classes

[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-Fc73mfqL-1642959089945)(X:\Users\Administrator\Desktop\assets\image-20220105171709639.png)]

The feature of the file system implementation class is that configLocation writes the location of the configuration file on the disk.

configLocation in ClassPath writes the file name of the configuration file (the default path is under src).

2.3 IOC operation Bean Management (based on xml)

2.3.1 what is Bean management

Bean management refers to two operations:

(1) Spring create object

(2) Spring injection properties

There are two ways to manage beans:

(1) Implementation of configuration file based on xml

(2) Annotation based implementation

2.3.2 creating objects based on xml

For example, bean1 XML file

 <bean id="user" class="com.atguigu.spring5.User"></bean>

(1) In the spring configuration file, you can create objects by using bean tags and adding corresponding attributes to the tags.

(2) There are many properties in the bean tag:

id attribute: get an id for the object and use it when getting the object

Class attribute: class full path (package class path)

name attribute: it can take the identification of special symbols, which is rarely used at present.

(3) When creating an object, the default is to execute the construction method without parameters to complete the object creation.

2.3.3 attribute injection based on xml

(1) DI: dependency injection, that is, injection attributes. This is an implementation method in IOC, which needs to be injected on the basis of creating objects.

1. The first injection method: use the set method for injection

The first step is to create a class, define attributes and corresponding set methods

//Create attribute
    private String bname;
    private String bauthor;
//Create the set method corresponding to the property
    public void setBname(String bname) {
        this.bname = bname;
    }
    public void setBauthor(String bauthor) {
        this.bauthor = bauthor;
    }

The second step is to create a configuration object in the spring configuration file and configure attribute injection

<!--set Method injection properties-->
<bean id="book" class="com.atguigu.spring5.Book">
     <!--use property Complete attribute injection
         name:Attribute name in class;
         value: Values injected into attributes
     -->
    <property name="bname" value="Trisomy: Earth past"></property>
    <property name="bauthor" value="Liu Cixin"></property>
</bean>

Step 3: Test:

[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-X3hflAhc-1642959089947)(X:\Users\Administrator\Desktop\assets\image-20220105180926832.png)]

2. The second injection method: parametric structure injection

The first step is to create a class and define attributes, including creating parameterized construction methods corresponding to attributes

/**
 * Construct injection with parameters
 */
public class Orders {
    private String oname;
    private String address;

    public Orders(String oname, String address) {
        this.oname = oname;
        this.address = address;
    }
}

The second step is to create a configuration object in the spring configuration file and configure attribute injection

    <!--Injection attribute with parameter construction-->
    <bean id="orders" class="com.atguigu.spring5.Orders">
        <!--use constructor-arg Complete attribute injection with parameter structure
            name:Attribute name in class;
            value: Values injected into attributes
        -->
        <constructor-arg name="oname" value="abc"></constructor-arg>
        <constructor-arg name="address" value="Lala Lala"></constructor-arg>
        <!--Alternatively, injection can be performed in the following ways,0 And 1 represent the first and second parameters in the parametric construction method, respectively-->
        <constructor-arg index="0" value="abc"></constructor-arg>
        <constructor-arg index="1" value="abc"></constructor-arg>
    </bean>

Step 3: Test:

[the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-Db46leMk-1642959089948)(X:\Users\Administrator\Desktop\assets\image-20220105182306701.png)]

3 p namespace injection

Step 1: use p namespace injection to simplify xml based configuration

<beans 
       xmlns:p="http://www.springframework.org/schema/p"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

Step 2: perform attribute injection and operate in the bean tag

<bean id="book" class="com.atguigu.spring5.Book" p:bname="My trisomy" p:bauthor="anonymous person">
</bean>

4 injection control and special symbols

  1. Literal

    (1) null value

    <bean id="book" class="com.atguigu.spring5.Book">
            <property name="bname" value="Trisomy: Earth past"></property>
            <property name="bauthor" value="Liu Cixin"></property>
        	<!--injection null value-->
            <property name="bpress">
                <null/>
            </property>
    </bean>
    

    (2) Attribute values contain special symbols

    <!-- Attribute values contain special symbols
         1.hold<>Escape
         2.Write content with special symbols to CDATA
    -->
    <property name="bpress" ><value><![CDATA[<<Nanjing>>]]></value></property>
    

5 inject external bean s

What is the introduction of external bean s?

Call dao layer through service layer.

(1) Create two classes: service and dao

Step 1: create two packages, one dao and one service

Create a new UserService class to call dao's method.

Create a new UserDao interface and a new UserDaoImpl to implement the methods defined in the UserDao interface.

//UserService.java:
public class UserService {
    public void add(){
        System.out.println("service add...");
    }
}

//UserDao.java(interface)
public interface UserDao {
    public void update();
}

//UserDaoImpl.java:
public class UserDaoImpl implements UserDao {
    @Override
    public void update() {
        System.out.println("dao update...");
    }
}

(2) Call dao in service

public class UserService {
    public void add(){
        System.out.println("service add...");
        //1. Create UserDao object and call
        UserDao userDao = new UserDaoImpl();
        userDao.update();
    }
}

(3) Configure in the spring configuration file

UserService.java:
public class UserService {
    //Create UserDao type attribute and generate set method
    private UserDao userDao;
    public void setUserDao(UserDao userDao) {
        this.userDao = userDao;
    }
    public void add(){
        System.out.println("service add...");
        //1. Create UserDao object and call
        userDao.update();
    }
}

bean2.xml:
<!--1.service and dao objects creating-->
<bean id="userService" class="com.atguigu.spring5.service.UserService">
    <!--injection userDao object
        name Attribute value: the name of the attribute in the class
        ref Properties: Creating userDao Object bean Tagged id value
    -->
    <property name="userDao" ref="userDaoImpl"></property>
</bean>
<bean id="userDaoImpl" class="com.atguigu.spring5.dao.UserDaoImpl"></bean>

(4) Testing

TestBean.java:
public class TestBean {
    @Test
    public void testAdd(){
        ApplicationContext context =
                new ClassPathXmlApplicationContext("bean2.xml");

        UserService userService = context.getBean("userService", UserService.class);
        userService.add();
    }
}

6 injection of internal bean s and cascading assignment

(1) One to many relationships: departments and employees

One department corresponds to multiple employees, and one employee belongs to one department.

The Department is one, and there are many employees

(2) Represents a one to many relationship between entity classes

Step 1: create a new bean package, create a department class and an employee class, and define properties and Setter methods respectively

Dept.java:
public class Dept {
    private String dname;

    public void setDname(String dname) {
        this.dname = dname;
    }
}

Emp.java:
public class Emp {
    private String ename;
    private String gender;

    public void setEname(String ename) {
        this.ename = ename;
    }
    public void setGender(String gender) {
        this.gender = gender;
    }
}

Step 2: in the employee category, the employee belongs to a department and is represented by an object

Emp.java:(add)
    //Employees belong to a department and are represented in object form
    private Dept dept;
    public void setDept(Dept dept) {
        this.dept = dept;
    }

(3) Configure in the Spring configuration file

New bean3 XML, complete Dept and Emp

    <!--inside bean-->
    <bean id="emp" class="com.atguigu.spring5.bean.Emp">
        <!--First set two common properties-->
        <property name="ename" value="lucy"></property>
        <property name="gender" value="female"></property>
        <!--Set object type properties-->
        <property name="dept">
            <bean id="dept" class="com.atguigu.spring5.bean.Dept">
                <property name="dname" value="Security Department"></property>
            </bean>
        </property>
    </bean>

(4) Testing

Dept.java adds the toString method of dname so that there is value output

    @Override
    public String toString() {
        return "Dept{" +
                "dname='" + dname + '\'' +
                '}';
    }

Emp. Add the add method in Java to output the attribute value;

    public void add(){
        System.out.println(ename + "::" + gender + "::" + dept);
    }

Add test method:

    public void testBean2(){
        ApplicationContext context =
                new ClassPathXmlApplicationContext("bean3.xml");

        Emp emp = context.getBean("emp", Emp.class);
        emp.add();
    }

Injection attribute cascade assignment

(1) Create bean4, cascade assignment

(Writing method I)
	<bean id="emp" class="com.atguigu.spring5.bean.Emp">
        <property name="ename" value="Nancy"></property>
        <property name="gender" value="female"></property>

        <!--Cascade assignment-->
        <property name="dept" ref="dept"></property>
    </bean>
    <bean id="dept" class="com.atguigu.spring5.bean.Dept">
        <property name="dname" value="Ministry of Communications"></property>
    </bean>
 
(Writing method 2)
 generate dept of get method
public Dept getDept() {
   return dept;
}

The premise is that it needs to be generated in advance get method
    <bean id="emp" class="com.atguigu.spring5.bean.Emp">
        <property name="ename" value="Nancy"></property>
        <property name="gender" value="female"></property>

        <!--Cascade assignment-->
        <property name="dept.dname" value="Network Department"></property>
    </bean>

(2) Testing

ditto.

7. XML injection collection attributes

1. Inject array type properties

2. Inject List collection type properties

3. Injection Map collection

public class Stu {
    //1. Array type attribute
    private String[] courses;
    public void setCourses(String[] courses) {
        this.courses = courses;
    }

    //2.List collection type attribute
    private List<String> list;
    public void setList(List<String> list) {
        this.list = list;
    }

    //3. Create Map type attribute
    private Map<String,String> maps;
    public void setMaps(Map<String, String> maps) {
        this.maps = maps;
    }

    //4. Create Set collection type attribute
    private Set<String> sets;
    public void setSets(Set<String> sets) {
        this.sets = sets;
    }

    public void test(){
        System.out.println((Arrays.toString(courses)));
        System.out.println(list);
        System.out.println(maps);
        System.out.println(sets);
    }

XML file configuration

    <!--Collection type attribute injection-->
    <bean id="stu" class="com.atguigu.spring5.collectiontype.Stu">
        <!--Array type attribute injection-->
        <property name="courses">
            <array>
                <value>discrete mathematics </value>
                <value>data structure</value>
            </array>
        </property>
        <!--list Type attribute injection-->
        <property name="list">
            <list>
                <value>Zhang San</value>
                <value>Xiao Zhang</value>
            </list>
        </property>
        <!--map Attribute injection-->
        <property name="maps">
            <map>
                <entry key="MATH" value="math"></entry>
                <entry key="DAST" value="dast"></entry>
            </map>
        </property>
        <!--set Type attribute injection-->
        <property name="sets">
            <set>
                <value>MYSQL</value>
                <value>Redis</value>
            </set>
        </property>
    </bean>

test

public class TestSpring5Demo1 {
    @Test
    public void testCollection(){
        ApplicationContext context =
                new ClassPathXmlApplicationContext("bean1.xml");
        context.getBean("stu", Stu.class);
        Stu stu = context.getBean("stu", Stu.class);
        stu.test();
    }
}

[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-9tCOXuOM-1642959089950)(X:\Users\Administrator\Desktop\assets\image-20220112160939203.png)]

4. Set the object type value in the collection

New course class

Course.java
public class Course {
    private String cname;
    public void setCname(String cname) {
        this.cname = cname;
    }
    @Override
    public String toString() {
        return "Course{" +
                "cname='" + cname + '\'' +
                '}';
    }
}
Stu.java
    //Students learn many courses
    public List<Course> courseList;
    public void setCourseList(List<Course> courseList) {
        this.courseList = courseList;
    }
bean1.xml:
        <!--injection list Collection type, value is object-->
        <property name="courseList">
            <list>
                <ref bean="course1"></ref>
                <ref bean="course2"></ref>
            </list>
        </property>

    </bean>
    <!--Create multiple course object-->
    <bean id="course1" class="com.atguigu.spring5.collectiontype.Course">
        <property name="cname" value="Spring5"></property>
    </bean>
    <bean id="course2" class="com.atguigu.spring5.collectiontype.Course">
        <property name="cname" value="Mybatis"></property>
    </bean>

test

[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-aB5j6QwT-1642959089952)(X:\Users\Administrator\Desktop\assets\image-20220112180723757.png)]

5. Extract the set injection part

(1) Introducing the namespace util into the spring configuration file

<?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:util="http://www.springframework.org/schema/util"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
                           http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">
</beans>

(2) Use util tag to complete list collection injection and extraction

    <!--1.extract list Collection type attribute injection-->
    <util:list id="bookList">
        <value>CET6 English</value>
        <value>IELTS</value>
        <value>TOEFL</value>
    </util:list>

    <!--2.extract list Collection type attribute injection usage-->
    <bean id="book" class="com.atguigu.spring5.collectiontype.Book">
        <property name="list" ref="bookList"></property>
    </bean>

test

    public void testCollection(){
        ApplicationContext context =
                new ClassPathXmlApplicationContext("bean2.xml");
        context.getBean("book", Book.class);
        Book book = context.getBean("book", Book.class);
        book.test();
    }

[the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-TikO2s99-1642959089955)(X:\Users\Administrator\Desktop\assets\image-20220112223046695.png)]

8 Factory Bean

Ordinary beans are like this:

adopt id Get object book Examples of, class Get path
<bean id="book" class="com.atguigu.spring5.collectiontype.Book">
        <property name="list" ref="bookList"></property>
</bean>

The characteristics of ordinary bean s are:

The bean type defined in the configuration file is the return type

Factory bean s are characterized by:

The bean type defined in the configuration file can be different from the return type

The first step is to create a MyBean class, which is used as a factory bean to implement the interface FactoryBean

<bean id="myBean" class="com.atguigu.spring5.factorybean.MyBean"></bean>

The second step is to implement the method in the interface and the return bean type defined in the implemented method

public class MyBean implements FactoryBean<Course>{
    //Define return Bean
    //I define mybean, but I return course instead of mybean
    @Override
    public Course getObject() throws Exception {
        Course course = new Course();
        course.setCname("abc");
        return course;
    }

    @Override
    public Class<?> getObjectType() {
        return null;
    }

    @Override
    public boolean isSingleton() {
        return false;
    }
}

Step 3: Test:

    public void testCollection(){
        ApplicationContext context =
                new ClassPathXmlApplicationContext("bean3.xml");
        Course course = context.getBean("myBean", Course.class);
        System.out.println(course);
    }

9 scope of bean

1. In Spring, set whether to create a Bean instance as a single instance or multiple instances.

[the external link image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-9jlO0nTS-1642959089956)(X:\Users\Administrator\Desktop\assets\image-20220114212924936.png)]

[the external link image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-NsBg3yoP-1642959089958)(X:\Users\Administrator\Desktop\assets\image-20220114212946871.png)]

If the address printed is the same, it indicates that it is a single instance.

2. In Spring, beans are single instance by default.

3. How to set single instance or multi instance?

(1) In the bean tag of the Spring configuration file, there is a property (scope) to set single instance or multi instance.

(2) There are multiple scope attribute values

The first value, the default value scope = "singleton", indicates that it is a single instance object

The second value, prototype, represents a multi instance object

<bean id="book" class="com.atguigu.spring5.collectiontype.Book" scope="prototype">
        <property name="list" ref="bookList"></property>
</bean>

[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-X8YgTnoD-1642959089959)(X:\Users\Administrator\Desktop\assets\image-20220114213926342.png)]

(3) The difference between singleton and prototype

The first is singleton single instance and prototype multi instance

Second, when the scope value is set to singleton, loading the spring configuration file will create a single instance object

When you set the scope value to prototype, you do not create an object when loading the spring configuration file, but create a multi instance object when calling the getBean method

10 Bean life cycle

Life cycle refers to the process from object creation to object destruction

(1) Create bean instance through constructor (no parameter construction)

public class Orders {
    private String oname;
    //Nonparametric construction
    public Orders() {
        System.out.println("The first step is to perform parameterless construction creation bean example");
    }
    public void setOname(String oname) {
        this.oname = oname;
    }
}

(2) Set values for bean properties and references to other beans (call the set method)

    public void setOname(String oname) {
        this.oname = oname;
        System.out.println("Step 2, call set Method to set the property value");
    }

(3) Call the initialization method of the bean (configuration required)

    public void initMethod(){
        System.out.println("Step 3: execute the initialization method");
    }

(4) The bean is ready to use (the object is obtained)

(5) When the container is closed, the bean destruction method (the method that needs to be configured for destruction) is called

11 automatic assembly

What is automatic assembly?

Spring automatically injects the assembled attribute values according to the specified assembly rules, attribute names or attribute types.

Demonstrate the automatic assembly process

    <!--
    Realize automatic assembly, bean Label properties autowire,Used to configure automatic assembly
    autowire There are two values:
        byName Inject values based on attribute names bean of id The value and class attribute name should be the same
        byType Inject according to attribute type
    -->
    <bean id="emp" class="com.atguigu.spring5.autowire.Emp" autowire="byName">
    </bean>

    <bean id="dept" class="com.atguigu.spring5.autowire.Dept"></bean>

12 external profile

Method 1: directly configure database information

(1) Configure Druid connection pool

(2) Introducing Druid connection pool dependent jar package

    <!--Configure connection pool directly-->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
        <property name="url" value="jdbc:mysql://localhost:3306/userDb"></property>
        <property name="username" value="root"></property>
        <property name="password" value="root"></property>
    </bean>

Method 2: import an external property file to configure the database connection pool

(1) Create an external properties file, a properties format file, write the database information (jdbc.properties) and put it in the src directory

[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-niB5kH0d-1642959089961)(X:\Users\Administrator\Desktop\assets\image-20220117233306851.png)]

prop.driverClass=com.mysql.jdbc.Driver
prop.url=jdbc:mysql://localhost:3306/userDb
prop.userName=root
prop.password=root

(2) Introduce the external properties property file into the spring configuration file -- introduce the context namespace

<?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">


    <!--Import external properties file-->
    <context:property-placeholder location="classpath:jdbc.properties"/>

    <!--Configure connection pool-->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="driverClassName" value="${prop.driverClass}"></property>
        <property name="url" value="${prop.url}"></property>
        <property name="username" value="${prop.userName}"></property>
        <property name="password" value="${prop.password}"></property>
    </bean>
</beans>

2.4 IOC operation Bean Management (annotation based)

1. What is annotation

(1) Annotation is a code special tag, format: @ annotation name (attribute name = attribute value, attribute name = attribute value...)

(2) Use annotations, which act on classes, methods and attributes

(3) Purpose of using annotations: to simplify xml configuration

2. Spring provides annotations for creating objects in Bean management

The following four annotation functions are the same and can be used to create bean instances

(1)@Component

(2) @ Service (generally used in the business Service layer)

(3) @ Controller (generally used in the web layer)

(4) @ Repository (generally used in dao layer)

3. Object creation based on annotation

The first step is to introduce dependency

Spring-aop-5.2.6 RELEASE. Jar import

Step 2: start component scanning

introduce context Namespace
    <!--Turn on component scanning-->
    <!--1.The first way to scan multiple packages is to connect the paths of two packages with commas-->
    <!--2.The second way is to write the path of the parent package directly!-->
    <context:component-scan base-package="com.atguigu.spring5.dao, com.atguigu.spring5.service"></context:component-scan>
    <context:component-scan base-package="com.atguigu"></context:component-scan>

The third step is to create a class and add an object annotation on the class

package com.atguigu.spring5.service;

import org.springframework.stereotype.Service;

//In the annotation, the value attribute value can not be written. The default is the class name, with the first letter in lowercase
@Service(value="userService") //Same as < bean id = "userservice" class = "" > < / bean >
public class UserService {
    public void add(){
        System.out.println("Service add..");
    }
}

Step 4: Test

public class TestSpring5Demo1 {
    @Test
    public void testService(){
        ApplicationContext context
                = new ClassPathXmlApplicationContext("bean1.xml");
        UserService userService = context.getBean("userService", UserService.class);
        System.out.println(userService);
        userService.add();
    }
}

1 component scanning configuration

<?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"
       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">
    <!--Turn on component scanning-->
    <!--1.The first way to scan multiple packages is to connect the paths of two packages with commas-->
    <!--2.The second way is to write the path of the parent package directly!-->
    <context:component-scan base-package="com.atguigu.spring5.dao, com.atguigu.spring5.service"></context:component-scan>
    <context:component-scan base-package="com.atguigu"></context:component-scan>

    <!--Example 1
        use-default-filters="false"Indicates that the default is not used now filter,Self configuration filter
        context:include-filter Used to set what to scan, for example expression=....Controller,Scan tape only Controller Notes for.
    -->
    <context:component-scan base-package="com.atguigu" use-default-filters="false">
        <context:include-filter type="annotation"
                                expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>

    <!--Example 2
        Set what content is not scanned. The following example is not scanned controller Notes for.
    -->
    <context:component-scan base-package="com.atguigu">
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>
</beans>

2 attribute injection

(1) AutoWired: auto assemble according to attribute type

The first step is to create the service and dao objects, and add the creation object annotation in the service and dao classes

The second step is to inject dao objects into the service, add dao type attributes to the service class, and use annotations on the attributes

//Dao implementation class
@Repository
public class UserDaoImpl implements UserDao{
    @Override
    public void add() {
        System.out.println("dao add..");
    }
}

public class UserService {
    //To define dao type attributes, you do not need to add set methods and add injection attribute annotations
    @Autowired
    private UserDao userDao;
    public void add(){
        System.out.println("Service add..");
        userDao.add();
    }
}

(2) Qualifier: inject according to the name. The @ qualifier annotation is used together with @ Autowired above

//Define dao type properties
//There is no need to add a set method
//Add injection attribute annotation
@Autowired //Injection according to type
//Inject according to the name (the purpose is to distinguish between multiple implementation classes under the same interface, which cannot be selected according to the type, resulting in an error!)
@Qualifier(value = "userDaoImpl1") 
private UserDao userDao;

(3) Resource: it can be injected according to type or name (it belongs to the annotation under javax package, not recommended!)

//@Resource / / inject according to type
@Resource(name = "userDaoImpl1") //Inject by name
private UserDao userDao;

(4) Value: inject common type attribute

@Value(value = "abc")
private String name

3 fully annotated development

(1) Create a configuration class to replace the xml configuration file

package com.atguigu.spring5.config;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@Configuration //As a configuration class, replace xml
@ComponentScan(basePackages = {"com.atguigu"})
public class SpringConfig {
}

(2) Write test class

public class TestSpring5Demo1 {
    @Test
    public void testService(){
        //Load configuration class
        ApplicationContext context
                = new AnnotationConfigApplicationContext(SpringConfig.class);
        UserService userService = context.getBean("userService", UserService.class);
        System.out.println(userService);
        userService.add();
    }
}

III AOP

1 basic concepts of AOP

(1) Aspect oriented programming (aspect oriented), AOP can isolate each part of business logic, reduce the coupling between each part of business logic, improve the reusability of program, and improve the efficiency of development.

(2) Popular Description: add new functions to the main functions without modifying the source code

(3) Use the login example to illustrate AOP
[the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-eAGstK4M-1642959089964)(X:\Users\Administrator\Desktop\assets200702135106266.png)]

2 AOP (underlying principle)

a) The underlying layer of AOP uses dynamic proxy. There are two situations of dynamic proxy:

In the first case, JDK dynamic agent is used; Create an interface to implement class proxy objects and enhance class methods
[the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-vx40fPVy-1642959089965)(X:\Users\Administrator\Desktop\assets200702135134128.png)]

In the second case, CGLIB dynamic agent is used; Create the proxy object of the subclass and enhance the method of the class
[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-dADakWvf-1642959089965)(X:\Users\Administrator\Desktop\assets20070213514980.png)]

3 JDK dynamic agent

1) Use JDK dynamic Proxy and use the methods in the Proxy class to create Proxy objects

Call newProxyInstance method, which has three parameters:

public static Object newProxyInstance(ClassLoader loader,
                                      Class<?>[] interfaces,
                                      InvocationHandler h)

First parameter, class loader

The second parameter is the class where the enhancement method is located. The interface implemented by this class supports multiple interfaces

The third parameter is to implement this interface InvocationHandler, create a proxy object and write the enhanced part
2) JDK dynamic agent code writing

① Create interfaces and define methods

public interface UserDao {
 public int add(int a,int b);
 public String update(String id);
}

② Create interface implementation classes and implement methods

package com.atguigu.spring5;

public class UserDaoImpl implements UserDao{
    @Override
    public int add(int a, int b) {
        return a+b;
    }

    @Override
    public String update(String id) {
        return id;
    }
}

4 AOP (terminology)

a) Join point: which methods in the class can be enhanced. These methods are called join points

b) Pointcuts: the methods that are actually really enhanced are called pointcuts

c) Notification (enhancement): the logical part of the actual enhancement is called notification and is divided into the following five types:

1) Pre notification 2) post notification 3) surround notification 4) exception notification 5) final notification

d) Aspect: the process of applying notifications to pointcuts

5 AOP (operation)

a) Spring frameworks generally implement AOP operations based on AspectJ. AspectJ is not a part of spring. It is an independent AOP framework. AspectJ and Spirng framework are generally used together for AOP operations

b) AOP operation based on AspectJ:

1) implementation based on xml configuration file (2) implementation based on annotation (use)

c) Import related jar packages

[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-U4H6Huh2-1642959089968)(X:\Users\Administrator\Desktop\assets\image-20220121102112144.png)]

d) The pointcut expression is as follows:

(1)Pointcut expression function: know which method in which class to enhance 
(2)Syntax structure: execution([Permission modifier] [Return type] [Class full path] [Method name]([parameter list]) )
(3)Examples are as follows:
    Example 1: Yes com.atguigu.dao.BookDao Class add Enhance
		execution(* com.atguigu.dao.BookDao.add(..))
 	Example 2: Yes com.atguigu.dao.BookDao Class
		execution(* com.atguigu.dao.BookDao.* (..))
    Example 3: Yes com.atguigu.dao All classes in the package and all methods in the class are enhanced
		execution(* com.atguigu.dao.*.* (..))

1 AspectJ annotation

1. Create a class and define methods in the class

public class User {
    public void add(){
        System.out.println("user add...");
    }
}

2. Create enhancement classes (write enhancement logic)

//Enhanced class
public class UserProxy{
    //Before advice 
    public void before(){
        System.out.println("before...");
    }
}

3. Configure notifications

(1) In the Spring configuration file, turn on annotation scanning

<?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"
       xmlns:aop="http://www.springframework.org/schema/aop"
       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
                           http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">

    <!-- Enable annotation scanning -->
    <context:component-scan base-package="com.atguigu.spring5.aopanno"></context:component-scan>
</beans>

(2) Creating User and UserProxy objects using annotations

@Component
public class UserProxy{
    //Before advice 
    public void before(){
        System.out.println("before...");
    }
}

@Component
public class User {
    public void add(){
        System.out.println("user add...");
    }
}

(3) Add the comment @ Aspect on the enhanced class

<!--open Aspect Generate proxy object-->
<aop:aspectj-autoproxy></aop:aspectj-autoproxy>

//Enhanced class
@Component
@Aspect //Generate proxy object
public class UserProxy{
    //Before advice 
    public void before(){
        System.out.println("before...");
    }
}

(4) Configure different types of notifications

1. In the enhanced class, add type annotation on the method as notification, and use pointcut expression configuration

//Enhanced class
@Component
@Aspect //Generate proxy object
public class UserProxy{
    //The before annotation indicates as a pre notification
    @Before(value = "execution(* com.atguigu.spring5.aopanno.User.add(..))")
    //Before advice 
    public void before(){
        System.out.println("before...");
    }

    @AfterReturning(value = "execution(* com.atguigu.spring5.aopanno.User.add(..))")
    //The post notification (return notification) does not notify when there is an exception
    public void afterReturning(){
        System.out.println("afterReturning...");
    }
    
    @After(value = "execution(* com.atguigu.spring5.aopanno.User.add(..))")
    //The final notification will be executed whether there are exceptions or not
    public void after(){
        System.out.println("after...");
    }

    @AfterThrowing(value = "execution(* com.atguigu.spring5.aopanno.User.add(..))")
    //Exception notification only when an exception occurs
    public void afterThrowing(){
        System.out.println("afterThrowing...");
    }

    @Around(value = "execution(* com.atguigu.spring5.aopanno.User.add(..))")
    //surround
    public void around(ProceedingJoinPoint proceedingJoinPoint) throws Throwable{
        System.out.println("Before surround...");
        //Enhanced method execution
        proceedingJoinPoint.proceed();
        System.out.println("After surround...");
    }
}

test

public class TestAop {
    @Test
    public void testAopAnno(){
        ApplicationContext context =
                new ClassPathXmlApplicationContext("bean1.xml");
        User user = context.getBean("user", User.class);
        user.add();
    }
}

(5) Same pointcut extraction

    //Same pointcut extraction
    @Pointcut(value = "execution(* com.atguigu.spring5.aopanno.User.add(..))")
    public void pointdemo(){

    }

    //The before annotation indicates that as a pre notification (the value value is directly changed to the method name extracted by the pointcut)
    @Before(value = "pointdemo()")
    //Before advice 
    public void before(){
        System.out.println("before...");
    }

(6) There are multiple enhancement classes to enhance the same method. Set the enhancement class priority @ order (value)

@Component
@Aspect
@Order(1)
public class PersonProxy {
    @Before(value = "execution(* com.atguigu.spring5.aopanno.User.add(..))")
    public void before(){
        System.out.println("person before...");
    }
}

2 AspectJ configuration file

Generally, annotations are used instead of xml configuration, so just understand it

<!--1,Create two classes, enhanced class and enhanced class, and create methods (the same as above)-->
<!--2,stay spring Create two class objects in the configuration file-->
<!--create object-->
<bean id="book" class="com.atguigu.spring5.aopxml.Book"></bean>
<bean id="bookProxy" class="com.atguigu.spring5.aopxml.BookProxy"></bean>
<!--3,stay spring Configure pointcuts in configuration files-->
<!--to configure aop enhance-->
<aop:config>
 <!--breakthrough point-->
 <aop:pointcut id="p" expression="execution(* com.atguigu.spring5.aopxml.Book.buy(..))"/>
 <!--Configuration section-->
 <aop:aspect ref="bookProxy">
 <!--The enhancement effect is on the specific method-->
 <aop:before method="before" pointcut-ref="p"/>
 </aop:aspect>
</aop:config>

IV JDBCTemplate

1. Concept and use of jdbctemplate

a) The Spring framework encapsulates JDBC and uses JdbcTemplate to facilitate database operation

b) Import related jar packages

c) Configure [database connection pool] in the spring configuration file

<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"
 destroy-method="close">
 <property name="url" value="jdbc:mysql:///test" />
 <property name="username" value="root" />
 <property name="password" value="root" />
 <property name="driverClassName" value="com.mysql.jdbc.Driver" />
</bean>

d) Configure the JdbcTemplate object and inject DataSource

<!-- JdbcTemplate object -->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
 <!--injection dataSource-->
 <property name="dataSource" ref="dataSource"></property><!--set Mode injection-->
</bean>

e) Create a service class, create a dao class, and inject a JDBC template object into dao

<!-- Component scan -->
<context:component-scan base-package="com.atguigu"></context:component-scan>
@Service
public class BookService {
 //Injection dao
 @Autowired
 private BookDao bookDao;
}

@Repository
public class BookDaoImpl implements BookDao {
 //Inject JdbcTemplate
 @Autowired
 private JdbcTemplate jdbcTemplate;
}

2. Jdbctemplate operation database (add)

a) Create entity class corresponding to database

b) Create service and dao

(1) Add database in dao

(2) Call the update method in the JdbcTemplate object to add

@Repository
public class BookDaoImpl implements BookDao {
 //Inject JdbcTemplate
 @Autowired
 private JdbcTemplate jdbcTemplate;
 //Add method
 @Override
 public void add(Book book) {
 //1. Create sql statement
 String sql = "insert into t_book values(?,?,?)";
 //2 call method implementation
 Object[] args = {book.getUserId(), book.getUsername(),book.getUstatus()};
 int update = jdbcTemplate.update(sql,args);
 System.out.println(update);
 }
}

3. Jdbctemplate operation database (modification and deletion)

//1. Modification
@Override
public void updateBook(Book book) {
 String sql = "update t_book set username=?,ustatus=? where user_id=?";
 Object[] args = {book.getUsername(), book.getUstatus(),book.getUserId()};
 int update = jdbcTemplate.update(sql, args);
 System.out.println(update);
}
//2. Delete
@Override
public void delete(String id) {
 String sql = "delete from t_book where user_id=?";
 int update = jdbcTemplate.update(sql, id);
 System.out.println(update);
}
//The "addition, deletion and modification" implemented by using the JdbcTemplate template calls the same "update" method

4. Jdbctemplate operation database (query returns a value)

//Number of query table records
@Override
public int selectCount() {
 String sql = "select count(*) from t_book";
//In queryForObject method: the first parameter represents -- sql statement; The second parameter represents -- return type class  
 Integer count = jdbcTemplate.queryForObject(sql, Integer.class);
 return count;
}

5. Jdbctemplate operation database (query returned object)

//Query return object
@Override
public Book findBookInfo(String id) {
 String sql = "select * from t_book where user_id=?";
 //Call method
/*
	queryForObject Method:
		First parameter: sql statement
		The second parameter: RowMapper is an interface. For returning different types of data, use the implementation classes in this interface to complete data encapsulation
		The third parameter: sql statement value
*/
 Book book = jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<Book>(Book.class), id);
 return book;
}

6. Jdbctemplate operation database (query return set)

//Scenario: query book list, paging
//Query return collection
@Override
public List<Book> findAllBook() {
 String sql = "select * from t_book";
 //Call method
 List<Book> bookList = jdbcTemplate.query(sql, new BeanPropertyRowMapper<Book>(Book.class));
 return bookList;
}

7. Jdbctemplate operation database (batch operation)

//Batch add
@Override
public void batchAddBook(List<Object[]> batchArgs) {
 String sql = "insert into t_book values(?,?,?)";
//First parameter of batchUpdate method: sql statement 		 The second parameter: List set, adding multiple record data
 int[] ints = jdbcTemplate.batchUpdate(sql, batchArgs);
 System.out.println(Arrays.toString(ints));
}

//Batch add test
List<Object[]> batchArgs = new ArrayList<>();
Object[] o1 = {"3","java","a"};
Object[] o2 = {"4","c++","b"};
Object[] o3 = {"5","MySQL","c"};
batchArgs.add(o1);
batchArgs.add(o2);
batchArgs.add(o3);
//Call batch add
bookService.batchAdd(batchArgs);

8. The jdbctemplate implements batch modification

//Batch modification (call the same method as batch addition)
@Override
public void batchUpdateBook(List<Object[]> batchArgs) {
 String sql = "update t_book set username=?,ustatus=? where user_id=?";
 int[] ints = jdbcTemplate.batchUpdate(sql, batchArgs);
 System.out.println(Arrays.toString(ints));
}

Let's learn about Mybatis ==

V transaction management

Temporarily unavailable

Vi What's new in spring 5

Temporarily unavailable

Keywords: Java Spring intellij-idea

Added by chieffan on Mon, 24 Jan 2022 05:01:32 +0200