Spring5 class notes

Posted by alexboyer on Wed, 02 Feb 2022 08:33:37 +0100

[the external chain picture transfer fails, and the source station may have anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-74WEIKgM-1622182523086)(Spring5 classroom pen. assets/v2-c7d94fabd9e1251acb3bba73458e3813_720w.jpg)]

Spring5

1.,Spring****

1.1 INTRODUCTION

  • Spring - > spring brings spring to open source software

  • In 2002, the prototype of Spring framework was launched for the first time: interface21 framework!

  • Based on the interface21 framework, Spring framework has been redesigned and continuously enriched its connotation. The official version of 1.0 was released on March 24, 2004

  • Spring's concept: it is easier to use the existing technology. It is a hodgepodge and integrates the existing technical framework!

  • SSH: Struct2 + Spring + Hibernate (fully automatic persistence framework)!

  • SSM: Spring MVC + Spring + mybatis (semi-automatic persistence framework, customizable and stronger)!

Spring official website: https://spring.io/projects/spring-framework#overview

Official download: https://repo.spring.io/release/org/springframework/spring/

GitHub: https://github.com/spring-projects/spring-framework

Spring Web MVC: Spring webmvc latest edition

pom configuration files for Spring Web MVC and spring JDBC:

<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>5.2.7.RELEASE</version>
</dependency>

<!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-jdbc</artifactId>
    <version>5.2.7.RELEASE</version>
</dependency>

1.2 advantages

  • Spring is an open source free framework (container)!
  • Spring is a lightweight, non intrusive framework!
  • Inversion of control (IoC), aspect oriented programming (AOP)
  • Support transaction processing and framework integration! (almost all popular frameworks on the market can be integrated)!

===To sum up: Spring is a lightweight inversion of control (IoC) and aspect oriented programming (AOP) framework===

1.3 composition

[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-82dsBX9I-1622182523090)(Spring5 class)
Pen assets/aHR0cHM6Ly9naXRlZS5jb20vd29fYmVsbC9QaWN0dXJlQmVkL3Jhdy9tYXN0ZXIvaW1hZ2UvU3ByaW5nNyVFNSVBNCVBNyVFNiVBOCVBMSVFNSU5RCU5Ny5wbmc)]

1.4. Expansion

Modern java development - > Spring based development!

[external chain picture transfer fails, and the source station may have anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-XzWblEuX-1622182523091)(Spring5 classroom pen. Assets / ahr0chm6ly9naxrlzs5jb20vd29fymvsbc9qawn0dxjlqmvkkl3jhdy9tyxn0zxivaw1hz2uvmjaymda4mdewmza4mjaucg5n)]

  • Spring Boot
    • A rapidly developed scaffold
    • Based on SpringBoot, you can quickly develop a single microservice
    • Agreement is greater than configuration!
  • Spring Cloud
    • SpringCloud is implemented based on SpringBoot!

Because now most companies are using SpringBoot for rapid development. The premise of learning SpringBoot is to fully master Spring and Spring MVC! The role of connecting the preceding and the following!

2. Derivation of IoC (control reversal) theory

Traditional call

  1. UserDao

    package dao;
    public interface UserDao {
    	void getUser();
    }
    
  2. UserDaoImp

    package dao;
    public class UserDaoImpl implements UserDao{
    	public void getUser() {
    		System.out.println("Get user data by default");	
    	}
    }
    
  3. UserSevice

    package Service;
    public interface UserService {
    	void getUser();
    }
    
  4. UserServiceImp

    package Service;
    import dao.UserDao;
    import dao.UserDaoImpl;
    
    public class UserServiceImpl implements UserService{
    		UserDao userDao = new UserDaoImpl();		
    		public void getUser(){
    			userDao.getUser();
    		}	
    }
    

test

package holle0;
import Service.UserService;
import Service.UserServiceImpl;

public class MyTest0 {
	public static void main(String[] args) {
		// What users actually call is the business layer, and they don't need to touch the dao layer
		UserService userService = new UserServiceImpl();
		userService.getUser();
	}
}

In our previous business, the needs of users may affect our original code. We need to modify the original code according to the needs of users! If the amount of program code is very large, the cost of modifying once is very expensive!

[the external chain picture transfer fails, and the source station may have anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-KaMSygmH-1622182523093)(Spring5 classroom pen. assets/aHR0cHM6Ly9naXRlZS5jb20vd29fYmVsbC9QaWN0dXJlQmVkL3Jhdy9tYXN0ZXIvaW1hZ2UvaW1hZ2UtMjAyMDA4MDExMjI3NDI1ODEucG5n)]
**Improvement: * * we use a Set interface. Revolutionary changes have taken place!

//Add a Set() method to the implementation class (UserServiceImpl) of the Service layer
//Use set to dynamically realize value injection!
//The DAO layer does not write the implementation class of which UserDao to call
//Instead, the Service layer calls the method to set the implementation class!
private UserDao userDao;
public void setUserDao(UserDao userDao){
    this.userDao = userDao;
}

The set() method actually dynamically changes the initialization part of userdao (new UserDaoImpl())

Add in the test

((UserServiceImpl)userService).setUserDao(new UserDaoImpl());
  • Previously, the program was actively creating objects! Control is in the hands of the program ape!
  • After using set injection, the program is no longer active, but becomes a passive receiving object! (the initiative is in the hands of the customer)

Essentially solved the problem, programmers no longer have to manage the creation of objects

The coupling of the system is greatly reduced, so we can focus more on the implementation of business

This is the prototype of IoC (control inversion). Inversion (understanding): the initiative is handed over to the user

[the external chain picture transfer fails. The source station may have anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-WgSoOZo1-1622182523094)(Spring5 classroom pen. Assets / ahr0chm6ly9naxrlzs5jb20vd29fymvsbc9qawn0dxjlqmvkkl3jhdy9tyxn0zxivaw1hz2uvaw1hz2utmjaymda4mdexmji4mdu3njkucg5n)]

IoC essence

[the external chain picture transfer fails, and the source station may have anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-FuYO6gAm-1622182523095)(Spring5 classroom pen. Assets / ahr0chm6ly9naxrlzs5jb20vd29fymvsbc9qawn0dxjlqmvkkl3jhdy9tyxn0zxivaw1hz2uvaw1hz2utmjaymda4mdexmjm1mtg5nzqucg5n)]
[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-7AwY9ewi-1622182523096)(Spring5 classroom pen. assets/aHR0cHM6Ly9naXRlZS5jb20vd29fYmVsbC9QaWN0dXJlQmVkL3Jhdy9tYXN0ZXIvaW1hZ2UvMjAyMDA4MDExMjMyMzUucG5n)]
[the external chain picture transfer fails, and the source station may have anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-Wz2zXqSY-1622182523096)(Spring5 classroom pen. assets/aHR0cHM6Ly9naXRlZS5jb20vd29fYmVsbC9QaWN0dXJlQmVkL3Jhdy9tYXN0ZXIvaW1hZ2UvaW1hZ2UtMjAyMDA4MDExMjMzNDgyMDcucG5n)]
[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-o6fXAeYp-1622182523097)(Spring5 classroom pen. assets/aHR0cHM6Ly9naXRlZS5jb20vd29fYmVsbC9QaWN0dXJlQmVkL3Jhdy9tYXN0ZXIvaW1hZ2UvaW1hZ2UtMjAyMDA4MDExMjM0NTA4OTcucG5n)]

3,HolleSpring

Import jar package in parent module

<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
	<groupId>org.springframework</groupId>
	<artifactId>spring-webmvc</artifactId>
	<version>5.2.7.RELEASE</version>
</dependency>

pojo's hello java

package pojo;

public class Hello {

	private String str;
	
	public String getStr() {
		return str;
	}

	public void setStr(String str) {
		this.str = str;
	}
	
	@Override
	public String toString() {
		return "Holle [str=" + str + "]";
	}
}

xml configuration in resource

<?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
        https://www.springframework.org/schema/beans/spring-beans.xsd">


    <!--stay Spring Create objects in Spring These are called bean
    	Type variable name = new type();
    	Holle holle = new Holle();
    	
    	bean = object(holle)
    	id = Variable name(holle)
    	class = new Object of(new Holle();)
    	property This is equivalent to setting values for attributes in an object,Give Way str="Spring"
    -->
    
    <bean id="hello" class="pojo.Hello">
        <property name="str" value="Spring"/>
    </bean>
</beans>

Test class MyTest

package holle1;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import pojo.Hello;

public class MyTest {

	public static void main(String[] args) {
		//Get the context object of Spring
		ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
		//Our objects can be managed in spring. We need to use them and just take them out directly
		Hello holle = (Hello) context.getBean("hello");
		System.out.println(holle.toString());
	}

}

The core is injected with set, so there must be the following se() method

//Hello class
public void setStr(String str) {
		this.str = str;
	}

reflection:

[the external chain picture transfer fails, and the source station may have anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-zFpNVe3u-1622182523097)(Spring5 classroom pen. Assets / ahr0chm6ly9naxrlzs5jb20vd29fymvsbc9qawn0dxjlqmvkkl3jhdy9tyxn0zxivaw1hz2uvaw1hz2utmjaymda4mdexnjuxntyntkucg5n)]
IoC: objects are created, managed and assembled by Spring!

Understanding in barrage review:

The original procedure is: you write the menu and buy the dishes. When the guests come, you fry the dishes and entertain them. It's equivalent to inviting someone to dinner
Now this procedure is: you tell the downstairs restaurant what dishes you want. When the guests come, the restaurant will deliver the dishes you need
IoC: cooking is no longer done by yourself, but entrusted to a third party__ Restaurant to do

The difference at this time is that if I need to cook other dishes, I don't need to make recipes and buy materials by myself, but tell the restaurant what dishes I want and when to send them

.

Try introducing Spring into the first module

<?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
        https://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="userDaomSql" class="dao.UserDaoMysqlImpl"></bean>

    <bean id="userServiceImpl" class="service.UserServiceImp">
        <!--ref quote spring A good object has been created in-->
        <!--value Is a specific value,Basic data type-->
        <property name="userDao" ref="userDaomSql"/>
    </bean>

</beans>

The first module is tested after improvement

package holle0;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import service.UserServiceImpl;

public class MyTest0 {
	public static void main(String[] args) {
		ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
		UserServiceImpl userServiceImpl = (UserServiceImpl) context.getBean("userServiceImpl");
		userServiceImpl.getUser();
	}
}

Summary:

All classes must be assembled with beans XML;

All bean s should be fetched through containers;

The bean obtained in the container is an object, which can be used to call the method;

4. How IoC creates objects

  1. Create objects using parameterless construction, default.
  2. Use parametric construction (as follows)

Subscript assignment

index refers to the subscript of the parameter in the parametric structure, starting from 0;

<?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
        https://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="user" class="pojo.User">
        <constructor-arg index="0" value="chen"/>
    </bean>
</beans>

Type assignment (not recommended)

<bean id="user" class="pojo.User">
    <constructor-arg type="java.lang.String" value="kuang"/>
</bean>

Directly through the parameter name (Master)

<bean id="user" class="pojo.User">
    <constructor-arg name="name" value="kuang"></constructor-arg>
</bean>
<!-- For example, the parameter name is name,Then there name="Specific value" -->

After registering the bean, the object is initialized (similar to the new class name ())

Barrage comments:

The name method also needs no parameter construction and set method, and the index and type only need parameter construction

Even if there are two new objects, there is only one instance (singleton mode: globally unique)

User user = (User) context.getBean("user");
User user2 = (User) context.getBean("user");
system.out.println(user == user2)//The result is true

Summary: when the configuration file is loaded, the objects managed in the container (< bean >) have been initialized

5. Spring configuration

5.1 alias

<bean id="user" class="pojo.User">
    <constructor-arg name="name" value="chen"></constructor-arg>
</bean>

<alias name="user" alias="userLove"/>
<!-- When used
	User user2 = (User) context.getBean("userLove");	
-->

5.2 Bean configuration

<!--id: bean The unique identifier of, which is equivalent to the object name we learned
class: bean Object's corresponding qualified name: package name+type
name: It's also an alias, and name Multiple aliases can be taken at the same time -->
<bean id="user" class="pojo.User" name="u1 u2,u3;u4">
    <property name="name" value="chen"/>
</bean>
<!-- When used
	User user2 = (User) context.getBean("u1");	
-->

5.3,import

import is generally used for team development. It can merge multiple configuration files into one

Suppose that there are multiple developers in the project, and these three people copy different class development. Different classes need to be registered in different bean s, which we can benefit from
import everyone's beans XML merged into a total!

  • Zhang San (beans.xm1)

  • Li Si (beans2.xm1)

  • Wang Wu (beans3.xm1)

  • applicationContext.xml

    <import resource="beans.xm1"/>
    <import resource="beans2.xml"/>
    <import resource="beans3.xm1"/>
    

When using, just use the general configuration directly

Barrage comments:

Create according to the import order in the general xml. The later imported object will overwrite the first imported object, and the final instantiated object will be the one in the later imported xml

6. Dependency injection (DI)

6.1. Constructor injection

Point 4 is mentioned

6.2. set mode injection [ key ]

Dependency injection: set injection!

  • Dependency: the creation of bean objects depends on the container
  • Injection: all attributes in the bean object are injected by the container

[environment construction]

  1. Complex type

    Address class

  2. Real test object

    Student class

  3. beans.xml

  4. test

    MyTest3

Student class

package pojo;

import java.util.*;
@Get
@Set
public class Student {
//Don't forget to write get and set methods (lombok annotation is also OK)
    private String name;
    private Address address;

    private String[] books;
    private List<String> hobbies;

    private Map<String, String> card;
    private Set<String> game;

    private Properties infor;
    private String wife;

    @Override
    public String toString() {
        return "Student{" +"\n"+
                "name='" + name + '\'' +"\n"+
                ", address=" + address.toString() +"\n"+
                ", books=" + Arrays.toString(books) +"\n"+
                ", hobbies=" + hobbies +"\n"+
                ", card=" + card +"\n"+
                ", game=" + game +"\n"+
                ", infor=" + infor +"\n"+
                ", wife='" + wife + '\'' +"\n"+
                '}';
    }
}

Address class

package pojo;

public class Address {

    private String address;

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

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

beans.xml

<?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
        https://www.springframework.org/schema/beans/spring-beans.xsd">

	<bean id="address" class="pojo.Address">
		<property name="address" value="address Hello" />
	</bean>

	<bean id="student" class="pojo.Student">
		<!--First, normal value injection -->
		<property name="name" value="name Hello" />
		<!--Second, ref injection -->
		<property name="address" ref="address" />

		<!--Array injection -->
		<property name="books">
			<array>
				<value>three countries</value>
				<value>Journey to the West</value>
				<value>Water Margin</value>
			</array>
		</property>

		<!--list List injection -->
		<property name="hobbies">
			<list>
				<value>sing</value>
				<value>jump</value>
				<value>rap</value>
				<value>Basketball</value>
			</list>
		</property>

		<!--map Key value pair injection -->
		<property name="card">
			<map>
				<entry key="username" value="root" />
				<entry key="password" value="root" />
			</map>
		</property>

		<!--set(Removable weight)injection -->
		<property name="game">
			<set>
				<value>wangzhe</value>
				<value>lol</value>
				<value>galname</value>
			</set>
		</property>

		<!--Null pointer null injection -->
		<property name="wife">
			<null></null>
		</property>

		<!--properties Constant injection -->
		<property name="infor">
			<props>
				<prop key="id">20200802</prop>
				<prop key="name">cbh</prop>
			</props>
		</property>
	</bean>
</beans>

MyTest3

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import pojo.Student;

public class MyTest3 {
	public static void main(String[] args) {
		ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
		Student stu = (Student) context.getBean("student");
		System.out.println(stu.toString());
	}	
}

6.3 expansion and injection

Official document location

[external chain picture transfer failed. The source station may have anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-IQRKJVu4-1622182523098)(Spring5 classroom pen. Assets / ahr0chm6ly9naxrlzs5jb20vd29fymvsbc9qawn0dxjlqmvkkl3jhdy9tyxn0zxivaw1hz2uvaw1hz2utmjaymda4mdixndi3mtcymtyucg5n)]

pojo add User class

package pojo;

public class User {
    private String name;
    private int id;
	public User() {
        
	}
	public User(String name, int id) {
		super();
		this.name = name;
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	@Override
	public String toString() {
		return "User [name=" + name + ", id=" + id + "]";
	}
}

Note: add the following two lines to beans

Using the p and c namespaces requires importing xml constraints

xmlns:p="http://www.springframework.org/schema/p"
xmlns:c="http://www.springframework.org/schema/c"

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

    <!--p Namespace injection/set Injection, you can directly inject the value of the attribute->property-->
    <bean id="user" class="pojo.User" p:name="cxk" p:id="20" >
    </bean>

    <!--c Namespace, which is injected by constructor, needs to be written with and without parameter construction methods->construct-args-->
    <bean id="user2" class="pojo.User" c:name="cbh" c:id="22"></bean>
</beans>

test

ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
User user = context.getBean("user",User.class);//If you determine the class object, you don't have to force it
System.out.println(user.toString());

6.4 Bean scope

[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-Lt1D66DK-1622182523099)(Spring5 classroom pen. Assets / ahr0chm6ly9naxrlzs5jb20vd29fymvsbc9qawn0dxjlqmvkkl3jhdy9tyxn0zxivaw1hz2uvaw1hz2utmjaymda4mdixmdexnjuucg5n)]

[the external chain picture transfer fails, and the source station may have anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-EO6lo1mc-1622182523100)(Spring5 classroom pen. assets/aHR0cHM6Ly9naXRlZS5jb20vd29fYmVsbC9QaWN0dXJlQmVkL3Jhdy9tYXN0ZXIvaW1hZ2UvaW1hZ2UtMjAyMDA4MDIxNDMzNDI1ODYucG5n)]

  1. Singleton mode (default)

    <bean id="user2" class="pojo.User" c:name="cxk" c:age="19" scope="singleton"></bean>
    1
    

[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-ahwj7aju-1622182523100)(Spring5 classroom pen. Assets / ahr0chm6ly9naxrlzs5jb20vd29fymvsbc9qawn0dxjlqmvkkl3jhdy9tyxn0zxivaw1hz2uvaw1hz2utmjaymda4mdixdiwmduucg5n)]
Bullet screen comment: the singleton mode is to put the object in the pool and take it out again. The same object instance is used

  1. Prototype pattern: every time you get from the container, a new object is generated!

    <bean id="user2" class="pojo.User" c:name="cxk" c:age="19" scope="prototype"></bean>
    1
    

[the external chain picture transfer fails. The source station may have anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-086XewMx-1622182523101)(Spring5 classroom pen. Assets / ahr0chm6ly9naxrlzs5jb20vd29fymvsbc9qawn0dxjlqmvkkl3jhdy9tyxn0zxivaw1hz2uvaw1hz2utmjaymda4mdixd4mjyymjcucg5n)]

  1. The rest of the request s, session s and application s can only be used in web opening!

7. Automatic assembly of Bean

  • Automatic assembly is a way for Spring to meet bean dependencies
  • Spring will automatically find in the context and automatically assemble properties for the bean

There are three ways to assemble in Spring

  1. Display configuration in xml

  2. Display configuration in java

  3. Implicit automatic assembly bean [important]

  4. Environment construction: a person has two pets

  5. byType auto assembly: byType will automatically find bean s with the same type as the set method parameter of its own object

    Ensure that all classes are unique (classes are globally unique)

  6. byName auto assembly: byName will automatically find the id corresponding to the value corresponding to its own object set

    Ensure that all IDs are unique and consistent with the values injected by set

    <!-- can't find id Same as multiple class -->
    <bean id="cat1" class="pojo.Cat"/>
    <bean id="cat2" class="pojo.Cat"/>
    <!-- can't find id=cat,And there are two Cat -->
    

7.1 test: automatic assembly

Cat class of pojo

public class Cat {
    public void shut(){
        System.out.println("miao");
    }
}

Dog class of pojo

public class Dog {

    public void shut(){
        System.out.println("wow");
    }

}

People class of pojo

package pojo;
public class People {
    
    private Cat cat;
    private Dog dog;
    private String name;

    public Cat getCat() {
        return cat;
    }

    public void setCat(Cat cat) {
        this.cat = cat;
    }

    public Dog getDog() {
        return dog;
    }

    public void setDog(Dog dog) {
        this.dog = dog;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
    @Override
    public String toString() {
        return "People{" +
                "cat=" + cat +
                ", dog=" + dog +
                ", name='" + name + '\'' +
                '}';
    }
}

xml configuration - > bytype auto assembly

<?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
        https://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="cat" class="pojo.Cat"/>
    <bean id="dog" class="pojo.Dog"/>
    
    <!--byType It will be automatically found in the container, which has the same properties as its own object bean
		For example, Dog dog; Then it will find pojo of Dog Class, and then conduct automatic assembly
	-->
    <bean id="people" class="pojo.People" autowire="byType">
        <property name="name" value="cbh"></property>
    </bean>

</beans>

xml configuration - > byname auto assembly

<bean id="cat" class="pojo.Cat"/>
<bean id="dog" class="pojo.Dog"/>
<!--byname Will automatically find in the container, and their own objects set Methodical set The following values correspond to id
  for example:setDog(),take set The following characters are used as id,Then id = dog Before automatic assembly
  
 -->
<bean id="people" class="pojo.People" autowire="byName">
	<property name="name" value="cbh"></property>
</bean>

Barrage comment: byName can only be taken in lowercase, but not in uppercase

7.2. Use notes to realize automatic assembly

jdk1.5 supported annotations, spring2 5 supported annotations

The introduction of annotation-based configuration raised the question of whether this approach is “better” than XML. The introduction of annotation based configuration raises the question of whether this approach is "better" than XML

  1. Import context constraint

xmlns:context="http://www.springframework.org/schema/context"

  1. Support for configuring annotations: < context: annotation config / >
<?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
        https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        https://www.springframework.org/schema/context/spring-context.xsd">

    <context:annotation-config/>
</beans>

7.2.1,@Autowired

byType is used by default. If it doesn't match, byName will be used

It can be used on attributes or set

We don't need to write the set method. The premise is that the automatically assembled properties are in the Spring container and comply with ByName automatic assembly

public class People {
    @Autowired
    private Cat cat;
    @Autowired
    private Dog dog;
    private String name;
}

@The Nullable field is marked with this annotation, indicating that the field can be empty

public name(@Nullable String name){

}

//Source code
public @interface Autowired { 
	boolean required() default true; 
}

If the require attribute of defined Autowire is false, it means that the object can be null, otherwise it is not allowed to be empty (false means that the assembly cannot be found and no exception is thrown)

7.2.2,@Autowired+@Qualifier

@@ Autowired+@Qualifier is required when Autowired cannot be assembled uniquely

If @ Autowired auto assembly environment is complex. When automatic assembly cannot be completed through an annotation, you can use @ Qualifier(value = "dog") to specify a unique id object

public class People {
    @Autowired
    private Cat cat;
    @Autowired
    @Qualifier(value = "dog")
    private Dog dog;
    private String name;
}

Barrage comments:

If the same object in the xml file is used by multiple bean s, Autowired cannot find it by type. You can use @ Qualifier to specify the id

7.2.3,@Resource

byName is used by default. If it doesn't match, byType will be used

public class People {
    Resource(name="cat")
    private Cat cat;
    Resource(name="dog")
    private Dog dog;
    private String name;
}

Barrage comments:

Autowired is byType, @ Autowired + @ qualifier = byType | byname

Autowired is byteType first. If it is unique, it will be injected. Otherwise, it will be searched by byname. resource is byname first. If it doesn't match, continue byType

difference:

@Difference between Resource and @ Autowired:

  • They are used for automatic assembly and can be placed in the attribute field
  • @Autowired is implemented by byType, and this object must exist! [common]
  • @Resource is implemented by byname by default. If the name cannot be found, it is implemented by byType! If both cannot be found, report an error! [common]
  • The execution order is different: @ Autowired is implemented by byType@ Resource is implemented by byname by default

8. Using annotation development

After spring 4, when developing with annotations, we must ensure the import of aop package
[the external chain picture transfer fails, and the source station may have anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-WzKKSvgH-1622182523101)(Spring5 classroom pen. Assets / ahr0chm6ly9naxrlzs5jb20vd29fymvsbc9qawn0dxjlqmvkkl3jhdy9tyxn0zxivaw1hz2uvaw1hz2utmjaymda4mdiymde5mjq0otaucg5n)]
Using annotations requires the constraint of importing contex t

<?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
        https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        https://www.springframework.org/schema/context/spring-context.xsd">

    <context:annotation-config/>

</beans>

8.1,bean

Barrage comments:
With < context: component scan >, another < context: annotation config / > tag can be removed because it has been included.

<!--Specify the package to be scanned, and the comments below the package will take effect
	Don't just sweep one com.kuang.pojo package--> 
<context:component-scan base-package="com.kuang"/>	 
<context:annotation-config/>
//@Component component
//Equivalent to < bean id = "user" classes "POJO. User" / > 
@Component
public class User {  
     public String name ="Qin Jiang";
}

8.2 how to inject @ value into attributes

@Component
public class User { 
    //Equivalent to < property name = "name" value = "kuangshen" / > 
    @value("kuangshen") 
    public String name; 
    
    //It can also be placed on the set method
    //@value("kuangshen")
    public void setName(String name) { 
        this.name = name; 
    }
}

8.3 notes derived

@Component has several derived annotations, which will be layered according to the mvc architecture in web development.

  • dao (@Repository)
  • service(@Service)
  • controller(@Controller)

The functions of these four annotations are the same. They all represent the registration of a class into the container

8.4. Automatic installation configuration

@Autowired: byType by default. If it doesn't match, byName will be used

@Nullable: the field is marked with this annotation, indicating that the field can be empty

@Resource: byName is used by default. If it doesn't match, byType will be used

8.5 scope @ scope

//Prototype mode, prototype mode, singleton mode
//scope("prototype") is equivalent to < bean scope = "prototype" > < / bean >
@Component 
@scope("prototype")
public class User { 
    
    //Equivalent to < property name = "name" value = "kuangshen" / > 
    @value("kuangshen") 
    public String name; 
    
    //It can also be placed on the set method
    @value("kuangshen")
    public void setName(String name) { 
        this.name = name; 
    }
}

8.6 summary

xml and annotations:

  • xml is more versatile, easy to maintain and suitable for any occasion
  • Annotations are not their own classes. They cannot be used and maintenance is complex

Best practices:

  • xml is used to manage bean s
  • Annotations are only used to complete attribute injection
  • To enable annotation support

9. Configure Spring in Java

Do not use the xml configuration of Spring, and leave it entirely to java!

A subproject of Spring, it has become the core function after Spring 4

[the external chain picture transfer fails, and the source station may have anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-NQZ0XIwW-1622182523102)(Spring5 classroom pen. Assets / ahr0chm6ly9naxrlzs5jb20vd29fymvsbc9qawn0dxjlqmvkkl3jhdy9tyxn0zxivaw1hz2uvaw1hz2utmjaymda4mdiymtu3nti4njgucg5n)]
Entity class: pojo's user java

//The annotation here means that this class is taken over by Spring and registered in the container 
@component 
public class User { 
    private String name;
    
    public String getName() { 
    	return name; 
    } 
    //Attribute injection value
    @value("QINJIANG')  
    public void setName(String name) { 
    	this.name = name; 
    } 
    @Override 
    public String toString() { 
        return "user{" + 
        "name='" + name + '\''+ 
        '}'; 
    } 
}

Barrage comment: either use @ Bean, or use @ Component and ComponentScan. The two effects are the same

Configuration file: Kuang. In config java

@Import(KuangConfig2.class), use @ import to contain kuangconfig2 java

//This will also be managed by the Spring container and registered in the container, because benmi is a @ Component 
// @Configuration table this is a configuration class, just like beans XML, similar to < beans > tags
@Configuration 
@componentScan("com.Kuang.pojo") //Turn on scanning
//@Import(KuangConfig2.class)
public class KuangConfig { 
    //Registering a bean is equivalent to a bean tag we wrote earlier 
    //The name of this method is equivalent to the id attribute - > getuser in the bean tag
    //The return value of this method is equivalent to the class attribute - > user in the bean tag
    @Bean 
    public User getUser(){ 
    	return new User(); //Is to return the object to be injected into the bean! 
    } 
}

Barrage comments: ComponentScan and @ Component("pojo") are used together

Test class

public class MyTest { 
    public static void main(String[ ] args) { 
    //If the configuration class method is completely used, we can only obtain the container through the annotation config context and load it through the class object of the configuration class! 
    ApplicationContext context = new AnnotationConfigApplicationContext(KuangConfig.Class); //class object
    User getUser =(User)context.getBean( "getUser"); //Method name getUser
    System.out.Println(getUser.getName()); 
    } 
}

Two descriptions of the same object problem will be created:

Bullet screen summary -- > @ Bean is equivalent to the object created by < Bean > tag, and the @ Component we learned earlier is the annotated object automatically created by spring, so here is equivalent to two User objects created. One is created by the Bean tag (@ Bean), and the other is the User object automatically created by scanning and then using @ Component and spring. Therefore, remove @ Bean here and start scanning. After that, use @ Component on the User header to automatically create the User object by spring

//This will also be managed by the Spring container and registered in the container, because benmi is a @ Component 
// @Configuration table this is a configuration class, just like beans XML, similar to < beans > tags
@Configuration 
@componentScan("com.Kuang.pojo") //Turn on scanning
//@Import(KuangConfig2.class)
public class KuangConfig { 
    //Registering a bean is equivalent to a bean tag we wrote earlier 
    //The name of this method is equivalent to the id attribute - > getuser in the bean tag
    //The return value of this method is equivalent to the class attribute - > user in the bean tag
    
    //@Bean 
    public User getUser(){ 
    	return new User(); //Is to return the object to be injected into the bean! 
    } 
}

Barrage comments: ComponentScan and @ Component("pojo") are used together

Test class

public class MyTest { 
    public static void main(String[ ] args) { 
    //If the configuration class method is completely used, we can only obtain the container through the annotation config context and load it through the class object of the configuration class! 
    ApplicationContext context = new AnnotationConfigApplicationContext(KuangConfig.Class); //class object
    User getUser =(User)context.getBean( "getUser"); //Method name getUser
    System.out.Println(getUser.getName()); 
    } 
}

Two descriptions of the same object problem will be created:

Bullet screen summary -- > @ Bean is equivalent to the object created by < Bean > tag, and the @ Component we learned earlier is the annotated object automatically created by spring, so here is equivalent to two User objects created. One is created by the Bean tag (@ Bean), and the other is the User object automatically created by scanning and then using @ Component and spring. Therefore, remove @ Bean here and start scanning. After that, use @ Component on the User header to automatically create the User object by spring

10. Dynamic agent

The proxy pattern is the bottom layer of spring AOP

Classification: dynamic agent and static agent

[the external chain picture transfer fails, and the source station may have anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-GrSB16V3-1622182523103)(Spring5 classroom pen. Assets / ahr0chm6ly9naxrlzs5jb20vd29fymvsbc9qawn0dxjlqmvkkl3jhdy9tyxn0zxivaw1hz2uvaw1hz2utmjaymda4mdmxmde0mjc4ndyucg5n)]

10.1 static agent

[the external chain picture transfer fails, and the source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-ArVrzpaX-1622182523103)(Spring5 classroom pen. Assets / ahr0chm6ly9naxrlzs5jb20vd29fymvsbc9qawn0dxjlqmvkkl3jhdy9tyxn0zxivaw1hz2uvaw1hz2utmjaymda4mdmxmde2mj2mje4njgucg5n)]
Code steps:

1. Interface

package pojo;
public interface Host {
	public void rent();
}

2. Real role

package pojo;
public class HostMaster implements Host{	
    
	public void rent() {
		System.out.println("The landlord wants to rent the house");
	}
}

3. Agent role

package pojo;
public class Proxy {

	public Host host;
	
	public Proxy() {
		
	}
	
	public Proxy(Host host) {
		super();
		this.host = host;
	}
	
	public void rent() {
		seeHouse();
		host.rent();
		fee();
		sign();
	}
	//House viewing
	public void seeHouse() {
		System.out.println("Look at the house");
	}
	//charge
	public void fee() {
		System.out.println("Intermediary fee");
	}
	//contract
	public void sign() {
		System.out.println("sign a contract");
	}		
}

4. Client access agent role

package holle4_proxy;

import pojo.Host;
import pojo.HostMaster;
import pojo.Proxy;

public class My {

	public static void main(String[] args) {
		//The landlord wants to rent the house
		Host host = new HostMaster();
		//The intermediary helps the landlord rent the house, but also charges a certain fee (add some operations that the landlord doesn't do)
		Proxy proxy = new Proxy(host);
		//I can't see the landlord, but I rented the house through the agent
		proxy.rent();
		
	}
}

[the external chain picture transfer fails. The source station may have anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-GcqLW4YS-1622182523104)(Spring5 classroom pen. assets/aHR0cHM6Ly9naXRlZS5jb20vd29fYmVsbC9QaWN0dXJlQmVkL3Jhdy9tYXN0ZXIvaW1hZ2UvaW1hZ2UtMjAyMDA4MDMxMDUyMjk0NzgucG5n)]
Code doubling: dozens of real characters have to write dozens of agents

AOP horizontal development

[the external chain picture transfer fails, and the source station may have anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-U5i3iDsi-1622182523105)(Spring5 classroom pen. Assets / ahr0chm6ly9naxrlzs5jb20vd29fymvsbc9qawn0dxjlqmvkkl3jhdy9tyxn0zxivaw1hz2uvaw1hz2utmjaymda4mdmxmte1mzk2mjeucg5n)]

10.2 dynamic agent

Dynamic agent is the same as static role. The bottom layer of dynamic agent is reflection mechanism

Dynamic proxy classes are dynamically generated, not written directly by us!

Dynamic agents (two categories): interface based and class based

  • Interface based: dynamic agent of JDK [using ing]
  • Class based: cglib
  • java bytecode implementation: javasit

Understand two classes
1. Proxy: proxy
2. InvocationHandler: call handler
[the external chain picture transfer fails, and the source station may have anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-hhVdK09u-1622182523106)(Spring5 classroom pen. Assets / ahr0chm6ly9naxrlzs5jb20vd29fymvsbc9qawn0dxjlqmvkkl3jhdy9tyxn0zxivaw1hz2uvaw1hz2utmjaymda4mdmxmti2mtk4njgucg5n)]

example:

Interface host java

//Interface
package pojo2;
public interface Host {
	public void rent();
	
}

Interface Host implementation class hostmaster java

//Interface implementation class
package pojo2;
public class HostMaster implements Host{	
	public void rent() {
		System.out.println("The landlord wants to rent a house");
	}
}

Handler class proxyinvocationhandler for agent role java

package pojo2;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

///Use this class to automatically generate agents
public class ProxyInvocationHandler implements InvocationHandler {

	// Foo f =(Foo) Proxy.NewProxyInstance(Foo. Class.GetClassLoader(),
	// new Class<?>[] { Foo.Class },
	// handler);

	// Proxy interface
	public HostMaster hostMaster ;
	
	public void setHostMaster(HostMaster hostMaster) {
		this.hostMaster = hostMaster;
	}

	// Get the generated proxy class 
	public Object getProxy() {
		// Newproxyinstance() - > generate proxy objects, so you don't need to write specific proxy classes
		// this. getClass(). Getclassloader() - > find the location where the class is loaded
		// hostMaster. getClass(). Getinterfaces() - > specific interface of the proxy
		// This - > represents the implementation class ProxyInvocationHandler of the interface InvocationHandler
		return Proxy.newProxyInstance(this.getClass().getClassLoader(), hostMaster.getClass().getInterfaces(), this);


	// Process proxy instances and return results
	public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
		seeHouse();
		// The essence of dynamic agent is to use reflection mechanism
        // invoke() executes the method it really wants to execute
		Object result = method.invoke(hostMaster, args);
		fee();
		return result;
	}

	public void seeHouse() {
		System.out.println("Look at the house");
	}

	public void fee() {
		System.out.println("Intermediary fee");
	}

}

User class my2 java

package holle4_proxy;

import pojo2.Host;
import pojo2.Host2;
import pojo2.HostMaster;
import pojo2.ProxyInvocationHandler;

public class My2 {

	public static void main(String[] args) {
        
		//Real role
		HostMaster hostMaster = new HostMaster();
        
		//Agent role, not now; Use the handler of the agent role to call the Host interface
		ProxyInvocationHandler pih = new ProxyInvocationHandler();
        
        //PIH - > hostmaster interface class - > host interface
		pih.setHostMaster(hostMaster);
        
		//Get newProxyInstance dynamically generated proxy class
		Host proxy = (Host) pih.getProxy();
		
		proxy.rent();

	}
}

Barrage comments:
When was the invoke method called?
When the proxy instance calls the method, the invoke method will be called. You can try debug ging

Change to universal agent class

///Use this class to automatically generate agents
public class ProxyInvocationHandler implements InvocationHandler {

	// Proxy interface
	public Object target;

	public void setTarget(Object target) {
		this.target = target;
	}

	// Get the generated proxy class - > fixed code
	public Object getProxy() {
		return Proxy.newProxyInstance(this.getClass().getClassLoader(), target.getClass().getInterfaces(), this);
	}

	// Process proxy instances and return results
	public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
		// The essence of dynamic agent is to use reflection mechanism
		// invoke() executes the method it really wants to execute
		Object result = method.invoke(target, args);
		return result;
	}

}

[the external chain picture transfer fails, and the source station may have anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-yoxhgcyH-1622182523107)(Spring5 classroom pen. Assets / ahr0chm6ly9naxrlzs5jb20vd29fymvsbc9qawn0dxjlqmvkl3jhdy9tyxn0zxivaw1hz2uvaw1hz2utmjaymda4mdmxmzmwzu0odqlmjatjtiwju1jthbjue4jue2jtgwjtgxjuu0jujcjuezju3kwjtg2lnbuzw)]

11,AOP

11.1. What is AOP

[the external chain picture transfer fails. The source station may have anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-qVjSUXso-1622182523108)(Spring5 classroom pen. Assets / ahr0chm6ly9naxrlzs5jb20vd29fymvsbc9qawn0dxjlqmvkkl3jhdy9tyxn0zxivaw1hz2uvaw1hz2utmjaymda4mdmxmzq1mdixnjklmjatjtiwqu9qlnbuzw)]

11.2 use of AOP in Spring

Provides declarative transactions that allow users to customize aspects

  • Crosscutting concerns: methods or functions that span multiple modules of an application. That is, the part that has nothing to do with our business logic, but we need to focus on is crosscutting concerns. Such as log, security, cache, transaction and so on
  • Aspect: a special object whose crosscutting concerns are modularized. That is, it is a class. (Log class)
  • Advice: work that must be completed in all aspects. That is, it is a method in a class. (method in Log class)
  • Target: the notified object. (generated proxy class)
  • Proxy: an object created after notification is applied to the target object. (generated proxy class)
  • Pointcut: the definition of the "place" where the aspect notification is executed. (the last two points: where to execute, for example: method.invoke())
  • Jointpoint: the execution point that matches the pointcut.

[the external chain picture transfer fails, and the source station may have anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-H9GYaGMv-1622182523109)(Spring5 classroom pen. Assets / ahr0chm6ly9naxrlzs5jb20vd29fymvsbc9qawn0dxjlqmvkkl3jhdy9tyxn0zxivaw1hz2uvaw1hz2utmjaymda4mdmxntqwndm5mdkucg5n)]
In spring AOP, crosscutting logic is defined through Advice. Spring supports five types of Advice:

[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-HOSohRKD-1622182523111)(Spring5 classroom pen. Assets / ahr0chm6ly9naxrlzs5jb20vd29fymvsbc9qawn0dxjlqmvkkl3jhdy9tyxn0zxivaw1hz2uvaw1hz2utmjaymda4mdmxmzu5mzc0mzuucg5n)]
That is, AOP adds new functions without changing the original code. (agent)

11.3. Using Spring to implement AOP

Import jar package

<!-- https://mvnrepository.com/artifact/org.aspectj/aspectjweaver -->
<dependency>
    <groupId>org.aspectj</groupId>
    <artifactId>aspectjweaver</artifactId>
    <version>1.9.4</version>
</dependency>

11.3.1 method 1: use the native spring interface

Spring API interface implementation

applicationContext.xml

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

    <!--register bean-->
    <bean id="userservice" class="service.UserServiceImpl"/>
    <bean id="log" class="log.Log"/>
    <bean id="afterLog" class="log.AfterLog"/>
	<!--Method 1: use native Spring API Interface-->
    <!--to configure aop,You also need to import aop constraint-->
    <aop:config>
        <!--Entry point: expression:expression, execution((location to execute)-->
        <aop:pointcut id="pointcut" expression="execution(* service.UserServiceImpl.*(..))"/>
        <!--UserServiceImpl.*(..) -> UserServiceImpl All methods under class(parameter)-->
        <!--Execute surround increase-->
        <aop:advisor advice-ref="log" pointcut-ref="pointcut"/>
        <aop:advisor advice-ref="afterLog" pointcut-ref="pointcut"/>
        <!-- surround,stay id="pointcut"Forward and backward cut -->
    </aop:config>

</beans>

Execution (return type, class name, method name (parameter)) - > execution(* com. Service., (...))

UserService.java

package service;
public interface UserService {   
	    public void add() ;
	    public void delete() ;
	    public void query() ;
	    public void update();
}

Implementation class of UserService userserviceimp java

package service;

public class UserServiceImpl implements UserService {

    public void add() {
        System.out.println("add increase");
    }
    public void delete() {
        System.out.println("delete Delete");
    }
    public void update() {
        System.out.println("update change");
    }
    public void query() {
        System.out.println("query check");
    }
}

Pre log java

package log;
import org.springframework.aop.MethodBeforeAdvice;
import java.lang.reflect.Method;

public class Log implements MethodBeforeAdvice {
    //Method: the method of the target object to execute
    //args: parameter
    //Target: target object
    public void before(Method method, Object[] args, Object target) throws Throwable {
        System.out.println(target.getClass().getName()+"of"+method.getName()+"Executed");
    }
}

Post afterlog java

package log;
import java.lang.reflect.Method;
import org.springframework.aop.AfterReturningAdvice;

public class AfterLog implements AfterReturningAdvice {
    //returnVaule: return value
    public void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable {
    	System.out.println("Yes"+method.getName()+"Method, the return value is"+returnValue);
    }
}

Test class MyTest5

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import service.UserService;

public class MyTest5 {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        //Note: the dynamic proxy is the interface
        UserService userService = (UserService) context.getBean("userservice");
        userService.add();
    }
}

11.3.2 method 2: implement AOP with user-defined classes

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

   <!--register bean-->
   <bean id="userservice" class="service.UserServiceImpl"/>
   <bean id="log" class="log.Log"/>
   <bean id="afterLog" class="log.AfterLog"/>
   <!-- Method 2: Customize -->
   <bean id="diy" class="diy.DiyPointcut"/>
   <aop:config>
       <!--Custom section-->
       <aop:aspect ref="diy">
           <!--breakthrough point-->
           <aop:pointcut id="point" expression="execution(* service.UserServiceImpl.*(..))"/>
           <aop:before method="before" pointcut-ref="point"/>
           <aop:after method="after" pointcut-ref="point"/>
       </aop:ascept>
   </aop:config>

</beans>
package diy;
public class DiyPointcut {

    public void before(){
        System.out.println("Insert to front");
    }

    public void after(){
        System.out.println("Insert to back");
    }
}
//test
public class MyTest5 {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        //Note: the dynamic proxy is the interface
        UserService userService = (UserService) context.getBean("userservice");
        userService.add();
    }
}

11.3.3 method 3: use annotation to realize

<?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:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
		https://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/aop
		https://www.springframework.org/schema/aop/spring-aop.xsd">
	
    <!-- register -->
    <bean id="userservice" class="service.UserServiceImpl"/>
    <!--Method 3: using annotation-->
    <bean id="diyAnnotation" class="diy.DiyAnnotation"></bean>
    
    <!-- Turn on automatic proxy 
		Implementation method: default JDK (proxy-targer-class="fasle")
    			 cgbin (proxy-targer-class="true")-->
	<aop:aspectj-autoproxy/>
    
</beans>

DiyAnnotation.java

package diy;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;

@Aspect  //Mark that this class is a facet
public class DiyAnnotation {
	
    @Before("execution(* service.UserServiceImpl.*(..))")
    public void before(){
        System.out.println("=====Before method execution=====");
    }

    @After("execution(* service.UserServiceImpl.*(..))")
    public void after(){
        System.out.println("=====After method execution=====");
    }

    //In surround enhancement, we can give a parameter to the floor heating pipe to represent the entry point we want to obtain
    @Around("execution(* service.UserServiceImpl.*(..))")
    public void around(ProceedingJoinPoint joinPoint) throws Throwable {
        System.out.println("Surround front");

        Object proceed = joinPoint.proceed();

        System.out.println("After surround");
    }
}

test

public class MyTest5 {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        //Note: the dynamic proxy is the interface
        UserService userService = (UserService) context.getBean("userservice");
        userService.add();
    }
}

Output result:

[the external chain picture transfer fails, and the source station may have anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-dmIUeydf-1622182523112)(Spring5 classroom pen. Assets / ahr0chm6ly9naxrlzs5jb20vd29fymvsbc9qawn0dxjlqmvkkl3jhdy9tyxn0zxivaw1hz2uvaw1hz2utmjaymda4mdmxnzu2ndiwnjqucg5n)]

12. Integrate mybatis

Mybatis spring official website: https://mybatis.org/spring/zh/

Configuration process of mybatis:

  1. Writing entity classes
  2. Write core configuration file
  3. Write interface
  4. Write mapper xml
  5. test

12.1. Mybatis spring mode I

  1. Write data source configuration
  2. sqISessionFactory
  3. sqISessionTemplate (equivalent to sqISession)
  4. You need to add an implementation class [new] to the interface
  5. Inject the implementation class written by yourself into Spring
  6. Test!

Import the jar package first

<dependencies>

    <!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>5.2.7.RELEASE</version>
    </dependency>

    <dependency>
        <groupId>org.aspectj</groupId>
        <artifactId>aspectjweaver</artifactId>
        <version>1.9.4</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-jdbc</artifactId>
        <version>5.2.7.RELEASE</version>
    </dependency>

    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>3.5.2</version>
    </dependency>

    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis-spring</artifactId>
        <version>2.0.4</version>
    </dependency>

    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>8.0.12</version>
    </dependency>

    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <version>1.18.12</version>
    </dependency>

</dependencies>
	
<!--stay build Medium configuration resources,To prevent the failure of resource export-->
<!-- Maven Solve the problem of static resource filtering -->
<build>
<resources>
    <resource>
        <directory>src/main/java</directory>
        <includes>
            <include>**/*.properties</include>
            <include>**/*.xml</include>
        </includes>
        <filtering>false</filtering>
    </resource>
    <resource>
        <directory>src/main/resources</directory>
        <includes>
            <include>**/*.properties</include>
            <include>**/*.xml</include>
        </includes>
        <filtering>false</filtering>
    </resource>
</resources>
</build>

[the external chain picture transfer fails. The source station may have anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-FGt5LoKC-1622182523113)(Spring5 classroom pen. Assets / ahr0chm6ly9naxrlzs5jb20vd29fymvsbc9qawn0dxjlqmvkkl3jhdy9tyxn0zxivaw1hz2uvaw1hz2utmjaymda4mdqxmjmta1njaucg5n)]
Writing order:
User -> UserMapper -> UserMapper.xml -> spring-dao.xml -> UserServiceImpl -> applicationContext.xml -> MyTest6

Code steps:

pojo entity class User

package pojo;
import lombok.Data;
@Data
public class User {
	private int id;
	private String name;
	private String pwd;
}

UserMapper, UserMapperImpl and UserMapper. In mapper directory xml

Interface UserMapper

package mapper;
import java.util.List;
import pojo.User;
public interface UserMapper {
	public List<User> getUser();
}

UserMapperImpl

package mapper;
import java.util.List;
import org.mybatis.spring.SqlSessionTemplate;
import pojo.User;

public class UserMapperImpl implements UserMapper{
	
	//All our operations used sqlSession in the past, but now we use SqlSessionTemplate;
	private SqlSessionTemplate sqlSessionTemplate;

	public void setSqlSessionTemplate(SqlSessionTemplate sqlSessionTemplate) {
		this.sqlSessionTemplate = sqlSessionTemplate;
	}

	public List<User> getUser() {
		UserMapper mapper = sqlSessionTemplate.getMapper(UserMapper.class);
		return mapper.getUser();
	}
}

UserMapper.xml (madness only stays when it gives face)

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
        
<!-- Binding interface -->
<mapper namespace="mapper.UserMapper">
	<select id="getUser" resultType="pojo.User">
		select * from mybatis.mybatis
	</select>
</mapper>

Mybatis config. In the resource directory xml,spring-dao.xml,applicationContext.xml

mybatis-config.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
  PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
  "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
	<!--Open log-->
	<settings>	
		<setting name="logImpl" value="STDOUT_LOGGING" />
	</settings>
	
	<!--You can alias an entity class -->
	<typeAliases> 
		<package name="pojo" />
	</typeAliases>

</configuration>

spring-dao.xml

<?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:aop="http://www.springframework.org/schema/aop"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
		https://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/aop
		https://www.springframework.org/schema/aop/spring-aop.xsd">
		
	<!--DataSource:use Spring Data source replacement Mybatis Configure additional data sources for: c3p0,dbcp,druid 
		This use Spring Provided JDBC: org.springframework.jdbc.datasource -->
	<!--data source -->
	<bean id="datasource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
		<property name="driverClassName"
			value="com.mysql.cj.jdbc.Driver" />
		<property name="url" value="jdbc:mysql://127.0.0.1:3306/mybatis?useSSL=false&amp;useUnicode=true&amp;characterEncoding=utf-8&amp;serverTimezone=Asia/Shanghai"/>
		<property name="username" value="root" />
		<property name="password" value="root" />
	</bean>
	
	<!--sqlSessionFactory-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="datasource" />
        <!--binding mybatis configuration file-->
        <property name="configLocation" value="classpath:mybatis-config.xml"/>
        <property name="mapperLocations" value="classpath:mapper/*.xml"/>
    </bean>

	<!-- sqlSessionTemplate This is what we used before: sqlsession -->
    <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
    	<!-- Only constructor injection can be used sqlSessionFactory Reason: it doesn't set method-->	
        <constructor-arg index="0" ref="sqlSessionFactory"/>
    </bean>
		
</beans>

applicationContext.xml

<?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:aop="http://www.springframework.org/schema/aop"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
		https://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/aop
		https://www.springframework.org/schema/aop/spring-aop.xsd">
    
	<!-- Import spring-dao.xml -->
	<import resource="spring-dao.xml"/>
	
    <bean id="userMapper" class="mapper.UserMapperImpl">
        <property name="sqlSessionTemplate" ref="sqlSession"></property>
    </bean>

</beans>

Test class

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import mapper.UserMapper;
import pojo.User;
public class MyTest6 {
	public static void main(String[] args) {
        
		ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
		
		UserMapper userMapper = (UserMapper) context.getBean("userMapper");
		
		for (User user : userMapper.getUser()) {
			System.out.println(user);
		}
	}
}

12.2. Mybatis spring mode II

UserServiceImpl2

package mapper;
import pojo.User;
import org.apache.ibatis.session.SqlSession;
import org.mybatis.spring.support.SqlSessionDaoSupport;
import java.util.List;
//Inherit SqlSessionDaoSupport class
public class UserMapperImpl2 extends SqlSessionDaoSupport implements UserMapper {
    public List<User> getUser() {
        SqlSession sqlSession = getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        return mapper.getUser();
        //Or one sentence: return getsqlsession() getMapper(UserMapper.class). getUser();
    }
}

spring-dao.xml

<?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:aop="http://www.springframework.org/schema/aop"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
		https://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/aop
		https://www.springframework.org/schema/aop/spring-aop.xsd">
		
	<!--DataSource:use Spring Data source replacement Mybatis Configuration of c3p0 dbcp druid 
		This use Spring Provided JDBC: org.springframework.jdbc.datasource -->
	<!--data source -->
	<bean id="datasource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
		<property name="driverClassName"
			value="com.mysql.cj.jdbc.Driver" />
		<property name="url" value="jdbc:mysql://127.0.0.1:3306/mybatis?useSSL=false&amp;useUnicode=true&amp;characterEncoding=utf-8&amp;serverTimezone=Asia/Shanghai"/>
		<property name="username" value="root" />
		<property name="password" value="root" />
	</bean>
	
	<!--sqlSessionFactory-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="datasource" />
        <!--binding mybatis configuration file-->
        <property name="configLocation" value="classpath:mybatis-config.xml"/>
        <property name="mapperLocations" value="classpath:mapper/*.xml"/>
    </bean>
    
	<!-- Method 2: SqlSessionTemplate You can stop writing-->
    
</beans>

applicationContext.xml

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

	<import resource="spring-dao.xml" />

	<!-- Method 2 -->
	<bean id="userMapper2" class="mapper.UserMapperImpl2">
		<property name="sqlSessionFactory" ref="sqlSessionFactory"></property>
	</bean>
</beans>

test

public class MyTest6 {
	public static void main(String[] args) {
		ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
		UserMapper userMapper = (UserMapper) context.getBean("userMapper2");
		for (User user : userMapper.getUser()) {
			System.out.println(user);
		}
	}
}

13. Declarative transactions

  • Treat a group of business as a business; Either all succeed or all fail!
  • Transaction is very important in project development, which involves the consistency of data
  • Ensure integrity and consistency

ACID principle of transaction:
1. Atomicity
2. Isolation
3. Consistency
4. Persistence

ACID reference article: https://www.cnblogs.com/malaikuangren/archive/2012/04/06/2434760.html

Transaction management in Spring

  • Declarative transaction: AOP
  • Programming transaction: transaction management needs to be carried out in the code

Declarative transaction

Import the jar package first

<dependencies>

    <!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>5.2.7.RELEASE</version>
    </dependency>

    <dependency>
        <groupId>org.aspectj</groupId>
        <artifactId>aspectjweaver</artifactId>
        <version>1.9.4</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-jdbc</artifactId>
        <version>5.2.7.RELEASE</version>
    </dependency>

    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>3.5.2</version>
    </dependency>

    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis-spring</artifactId>
        <version>2.0.4</version>
    </dependency>

    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>8.0.12</version>
    </dependency>

    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <version>1.18.12</version>
    </dependency>

</dependencies>
	
<!--stay build Medium configuration resources,To prevent the failure of resource export-->
<!-- Maven Solve the problem of static resource filtering -->
<build>
<resources>
    <resource>
        <directory>src/main/java</directory>
        <includes>
            <include>**/*.properties</include>
            <include>**/*.xml</include>
        </includes>
        <filtering>false</filtering>
    </resource>
    <resource>
        <directory>src/main/resources</directory>
        <includes>
            <include>**/*.properties</include>
            <include>**/*.xml</include>
        </includes>
        <filtering>false</filtering>
    </resource>
</resources>
</build>

Code steps:

pojo entity class User

package pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
	private int id;
	private String name;
	private String pwd;
}

UserMapper, UserMapperImpl and UserMapper. In mapper directory xml

Interface UserMapper

package mapper;
import java.util.List;
import org.apache.ibatis.annotations.Param;
import pojo.User;

public interface UserMapper {
	public List<User> getUser();
	
	public int insertUser(User user); 
	
	public int delUser(@Param("id") int id); 
}

UserMapperImpl

package mapper;

import pojo.User;
import org.apache.ibatis.session.SqlSession;
import org.mybatis.spring.support.SqlSessionDaoSupport;
import java.util.List;

public class UserMapperImpl extends SqlSessionDaoSupport implements UserMapper {
    public List<User> getUser() {
    	User user = new User(5,"Hello","ok");
    	insertUser(user);
    	delUser(5);
        SqlSession sqlSession = getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        return mapper.getUser();
        //Or return getsqlsession() getMapper(UserMapper.class). getUser();
    }
    //insert
	public int insertUser(User user) {
		return getSqlSession().getMapper(UserMapper.class).insertUser(user);
	}
	//delete
	public int delUser(int id) {
		return getSqlSession().getMapper(UserMapper.class).delUser(id);
	}
}

UserMapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
        
<!-- Binding interface -->
<mapper namespace="mapper.UserMapper">
	<select id="getUser" resultType="pojo.User">
		select * from mybatis.mybatis
	</select>
	
	<insert id="insertUser"  parameterType="pojo.User" >
		insert into  mybatis.mybatis (id,name,pwd) values (#{id},#{name},#{pwd})
	</insert>
	
	<delete id="delUser" parameterType="_int">
		deleteAAAAA from mybatis.mybatis where id = #{id}
		<!-- deleteAAAAA It was a deliberate mistake -->
	</delete>

</mapper>

Mybatis config. In the resource directory xml,spring-dao.xml,applicationContext.xml

mybatis-config.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
  PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
  "http://mybatis.org/dtd/mybatis-3-config.dtd">
<!-- configuration -->
<configuration>
	
	<!--Open log-->
	<settings>
		<setting name="logImpl" value="STDOUT_LOGGING" />
	</settings>
	
	<!--You can alias an entity class-->
	<typeAliases> 
		<package name="pojo" />
	</typeAliases>

</configuration>

spring-dao.xml (imported constraint)

<?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:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/tx
        https://www.springframework.org/schema/tx/spring-tx.xsd
        http://www.springframework.org/schema/aop
        https://www.springframework.org/schema/aop/spring-aop.xsd">
		
	<!--data source -->
	<bean id="datasource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
		<property name="driverClassName"
			value="com.mysql.cj.jdbc.Driver" />
		<property name="url" value="jdbc:mysql://127.0.0.1:3306/mybatis?useSSL=false&amp;useUnicode=true&amp;characterEncoding=utf-8&amp;serverTimezone=Asia/Shanghai"/>
		<property name="username" value="root" />
		<property name="password" value="root" />
	</bean>
	
	<!--sqlSessionFactory-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="datasource" />
        <!--binding mybatis configuration file-->
        <property name="configLocation" value="classpath:mybatis-config.xml"/>
        <property name="mapperLocations" value="classpath:mapper/*.xml"/>
    </bean>
	
	<!--Declarative transaction-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <constructor-arg ref="datasource" />
    </bean>

    <!--combination aop Implement transaction weaving-->
    <!--Configure notification classes for transactions-->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <!--Which methods are configured with transactions-->
        <!--What's new: the propagation feature of configuration transactions propagation-->
        <tx:attributes>
            <tx:method name="add" propagation="REQUIRED"/>
            <tx:method name="delete" propagation="REQUIRED"/>
            <tx:method name="update" propagation="REQUIRED"/>
            <tx:method name="query" read-only="true"/>
            <!-- *Number includes the above four methods:
            <tx:method name="*" propagation="REQUIRED"/> -->
        </tx:attributes>
    </tx:advice>

    <!--Configure transaction entry-->
    <aop:config>
        <aop:pointcut id="txpointcut" expression="execution(* mapper.*.*(..))"/>
        <aop:advisor advice-ref="txAdvice" pointcut-ref="txpointcut"/>
    </aop:config>
Hasty 
</beans>

applicationContext.xml

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

	<import resource="spring-dao.xml" />

	<bean id="userMapper" class="mapper.UserMapperImpl">
		<property name="sqlSessionFactory" ref="sqlSessionFactory"></property>
	</bean>
</beans>

Test class

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import mapper.UserMapper;import pojo.User;
public class MyTest7 {
	public static void main(String[] args) {

		ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
		
		UserMapper userMapper = (UserMapper) context.getBean("userMapper");
		
		for (User user : userMapper.getUser()) {
			System.out.println(user);
		}
	}
}

reflection:
Why transactions are needed?

  • If transactions are not configured, there may be inconsistent data submission;

  • If we don't configure declarative transactions in spring, we need to manually configure transactions in the code!
    ="configLocation" value="classpath:mybatis-config.xml"/>

    <tx:advice id="txAdvice" transaction-manager="transactionManager">


    tx:attributes
    <tx:method name="add" propagation="REQUIRED"/>
    <tx:method name="delete" propagation="REQUIRED"/>
    <tx:method name="update" propagation="REQUIRED"/>
    <tx:method name="query" read-only="true"/>

    </tx:attributes>
    </tx:advice>

    aop:config
    <aop:pointcut id="txpointcut" expression="execution(* mapper..(...))"/>
    <aop:advisor advice-ref="txAdvice" pointcut-ref="txpointcut"/>
    </aop:config>
    Hasty

applicationContext.xml

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

	<import resource="spring-dao.xml" />

	<bean id="userMapper" class="mapper.UserMapperImpl">
		<property name="sqlSessionFactory" ref="sqlSessionFactory"></property>
	</bean>
</beans>

Test class

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import mapper.UserMapper;import pojo.User;
public class MyTest7 {
	public static void main(String[] args) {

		ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
		
		UserMapper userMapper = (UserMapper) context.getBean("userMapper");
		
		for (User user : userMapper.getUser()) {
			System.out.println(user);
		}
	}
}

reflection:
Why transactions are needed?

  • If transactions are not configured, there may be inconsistent data submission;
  • If we don't configure declarative transactions in spring, we need to manually configure transactions in the code!
  • Transaction is very important in the development of the project, which involves the consistency and integrity of data!