Spring learning notes

Posted by maxelcat on Thu, 16 Dec 2021 03:14:42 +0100

1,Sping

1.1 INTRODUCTION

  • Spring: Spring - > brings spring to the software industry

  • In 2002, Rod Jahnson first launched the Spring framework prototype interface21 framework.

  • On March 24, 2004, the Spring framework was redesigned based on the interface 21 framework and released the official version of 1.0.

  • It's hard to imagine Rod Johnson's degree. He is a doctor at the University of Sydney. However, his major is not computer, but musicology.

  • Spring concept: make the existing technology more practical Itself is a hodgepodge, integrating existing framework technologies

  • SSH:Struct2+Sping+Hibernate

  • SSm:SpringMVC+Spring+Mybatis

Official website: http://spring.io/

Official download address: https://repo.spring.io/libs-release-local/org/springframework/spring/

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

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

</beans>

SpingMVC Web

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

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

1.2 advantages

1. Spring is an open source free framework, container

2. Spring is a lightweight framework, non - intrusive

3. Inversion of control (IOC), facing section (AOP)

4. Support transaction processing and framework integration

In one sentence:

Spring is a lightweight control inversion (IOC) and aspect oriented (AOP) container (framework).

1.3 composition

[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-l9m1mytr-1639618690682) (Ping note. assets/image-20210220165248101.png)]

  • Spring Boot

    • A rapid development of scaffolding
    • Based on SpringBoot, you can quickly develop a single microservice
    • Contract greater than configuration
  • Spring Cloud

    • Spring is implemented based on SpringBoot

Because most companies are now 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!

Disadvantages: after development for too long, it violates the original concept! Configuration is very cumbersome. Admit your mistake: "configuration hell!"

2. IOC theoretical derivation

Create a new blank maven project

Analysis and Implementation

Let's write a piece of code in our original way

1. First write a UserDao interface

public interface UserDao {
   public void getUser();
}

2. Then write Dao's implementation class

public class UserDaoImpl implements UserDao {
   @Override
   public void getUser() {
       System.out.println("Get user data");
  }
}

3. Then write the UserService interface

public interface UserService {
   public void getUser();
}

4. Finally, write the implementation class of Service

public class UserServiceImpl implements UserService {
   private UserDao userDao = new UserDaoImpl();

   @Override
   public void getUser() {
       userDao.getUser();
  }
}

5. Test it

@Test
public void test(){
   UserService service = new UserServiceImpl();
   service.getUser();
}

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

We use a Set interface implementation, which has undergone revolutionary changes

private UserDao userDao;

    //Dynamic value injection using set
    public void setUserDao(UserDao userDao){
        this.userDao=userDao;
    }
  • Before, the program was actively creating objects! Control is in the hands of programmers!
  • After using Set injection, programmers no longer have the initiative, but become passively accepted objects!

This idea essentially solves the problem. We programmers no longer manage the creation of objects. The coupling of the system is greatly reduced, and you can focus more on the implementation of business! This is the prototype of IOC!

IOC essence

Inversion of control (IoC) is a design idea. DI (dependency injection) is a method to realize IoC. Some people think that DI is just another way of saying IoC. In programs without IoC, we use object-oriented programming. The creation of objects and the dependencies between objects are completely hard coded. In programs, the creation of objects is controlled by the program itself. After the control is reversed, the creation of objects is transferred to a third party. Personally, I think the so-called control reversal is the reversal of the way to obtain dependent objects.

When configuring a Bean in XML, the definition information of the Bean is separated from the implementation, and the annotation method can integrate the two. The definition information of the Bean is directly defined in the implementation class in the form of annotation, so as to achieve the purpose of zero configuration.

Control inversion is a way to produce or obtain specific objects through description (XML or annotation) and through a third party. In Spring, IoC container implements control inversion, and its implementation method is dependency injection (DI).

3,HelloSpring

  • Who created the Hello object? [the Hello object is created by Spring]
  • How are the properties of the hello object set? The properties of the hello object are set by the Spring container

This process is called control reversal:

  • Control: who controls the creation of objects? Traditional application objects are created by the program itself. After using Spring, objects are created by Spring
  • Inversion: the program itself does not create an object, but becomes a passive receiving object

Dependency injection: it uses the set method to inject

IOC is a programming idea, from active programming to passive reception

You can browse the underlying source code through newClassPathXmlApplicationContext

OK, now, we don't need to change it in the program. To realize different operations, we only need to modify it in the xml configuration file. The so-called IoC is done in one sentence: objects are created, managed and assembled by Spring!

4. How IOC creates objects

1. Use parameterless construction to create objects. Default!

<!--use spring To create an object, in spring These appellations in Bean
    Type variable name = new Type ();
    Hello hello = new Hello;
    id = Variable name
    class = new Object of
    property It is equivalent to setting a value for the attribute in the object!
-->
    <bean id="hello" class="com.project.pojo.Hello">
        <property name="str" value="Spring"/>
    </bean>

2. Suppose we want to create an object with a parametric construct.

  • Subscript assignment
<!-- First: according to index Parameter subscript setting -->
<bean id="userT" class="com.kuang.pojo.UserT">
   <!-- index Refers to the construction method , Subscript starts at 0 -->
   <constructor-arg index="0" value="mingyue"/>
</bean>
  • type
<!-- The second is to create by type, which is not recommended -->
<bean id="userT" class="com.kuang.pojo.UserT">
   <constructor-arg type="java.lang.String" value="mingyue"/>
</bean>
  • Parameter name
<!-- The third method: set directly through the parameter name -->
<bean id="userT" class="com.kuang.pojo.UserT">
   <!-- name Refers to the parameter name -->
   <constructor-arg name="name" value="mingyue"/>
</bean>

Conclusion: when the configuration file is loaded. The managed objects have been initialized!

5. Spring configuration

5.1 alias

 <!--Alias. If an alias is added, we can also use the alias to get this object-->
 <alias name="user" alias="userNew"/>

5.2 Bean configuration

<!-- 
id :bean The unique identifier of, which is equivalent to the object name we learned
class: bean Fully qualified name corresponding to the object: package name + type
name:It's also an alias, and name Multiple aliases can be taken at the same time
property It is equivalent to setting a value for the attribute in the object!
-->
<bean id="userT" class="com.project.pojo.UserT" name="user2,u2,u3" >
      <property name="name" value="mingyue"></property>
</bean>

5.3 import

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

Suppose that there are multiple developers in the project. These three people are responsible for different class development. Different classes need to be registered in different beans. We can use import to import everyone's beans XML is merged into a total!

  • Zhang San
  • Li Si
  • Wang Wu
  • applicatContext.xml
<import resource="beans.xml"/>
<import resource="beans2.xml"/>
<import resource="beans3.xml"/>

When using, you can directly use the general configuration

6. Dependency injection

6.1 constructor injection

As already said

6.2 Set mode injection [ key ]

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

[environment construction]

1. Copy type

public class Address {
    private String address;

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

2. Real test object

public class Student {
    private String name;
    private Address address;
    private String[] books;
    private List<String> hobbys;
    private Map<String,String> card;
    private Set<String> games;
    private String wife;
    private Properties info;
}

3.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">

    <!--First, ordinary injection, value-->
    <bean id="student" class="com.project.pojo.Student">
        <property name="name" value="lsh"/>
    </bean>
</beans>

4. Testing

public class MyTest {
    public static void main(String[] args) {

        ApplicationContext Context = new ClassPathXmlApplicationContext("beans.xml");
        Student student = (Student) Context.getBean("student");
        System.out.println(student.toString());
    }
}

5. Improve injection information

    <bean id="address" class="com.project.pojo.Address">
        <property name="address" value="Guangdong"></property>
    </bean>

    <bean id="student" class="com.project.pojo.Student">
        <!--First, ordinary injection, value-->
        <property name="name" value="abc"/>
        <!--Second, Bean Injection, ref-->
        <property name="address" ref="address"/>
        <!--Array injection-->
        <property name="books">
            <array>
                <value>The Dream of Red Mansion</value>
                <value>Journey to the West</value>
                <value>Water Margin</value>
                <value>Romance of the Three Kingdoms</value>
            </array>
        </property>
        <!--List-->
        <property name="hobbys">
            <list>
                <value>listen to the music</value>
                <value>Knock code</value>
                <value>watch movie</value>
            </list>
        </property>
        <!--map-->
        <property name="card">
            <map>
                <entry key="ID" value="123456785334"/>
                <entry key="bank card" value="999456412345"/>
            </map>
        </property>
        <!--set-->
        <property name="games">
            <set>
                <value>LOL</value>
                <value>COC</value>
            </set>
        </property>
        <!--NULL-->
        <property name="wife">
            <null/>
        </property>
        <!--properties-->
        <property name="info">
            <props>
                <prop key="Student number">20190525</prop>
                <prop key="Gender">male</prop>
                <prop key="username">Xiao Ming</prop>
            </props>
        </property>
    </bean>

6.3 expansion mode injection

We can use P namespace and C namespace for injection

1. Official interpretation:

2. Use:

<?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, you can directly inject the value of the attribute: property -->
    <bean id="user" class="com.project.pojo.User" p:name="lsh" p:age="18"/>
    <!--c Namespace injection, which can be injected through the constructor: constructor -->
    <bean id="user2" class="com.project.pojo.User" c:age="18" c:name="Mad God"/>
    
</beans>

3. Test

    @Test
    public void test(){
        ApplicationContext context = new ClassPathXmlApplicationContext("userBeans.xml");
        User user =  context.getBean("user2",User.class);
        System.out.println(user);
    }
}

4. Precautions

P naming and C naming cannot be used directly, and xml constraints need to be imported

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

6.4 scope of bean

1. Singleton mode (Spring default mechanism)

<bean id="user2" class="com.project.pojo.User" c:age="18" c:name="Mad God" scope="singleton"/>

2. Prototype mode: each time you get from the container, a new object will be generated.

<bean id="accountService" class="com.something.DefaultAccountService" scope="prototype"/>

3. The rest of the request, session, application and can only be used in web development!

7. Automatic assembly of Bean

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

There are three ways to assemble in Spring

  1. Configuration displayed in xml
  2. Display configuration in java
  3. Hermit's automatic assembly bean [important]

7.1 testing

Environment construction: one person and two pets!

7.2 Byname auto assembly

    <!--byName: It will automatically find its own objects in the container context set Method beanid! -->
    <bean id="person" class="com.project.pojo.Person" autowire="byName">
        <property name="name" value="ADC"/>
    </bean>

7.3 ByType automatic assembly

    <bean  class="com.project.pojo.Cat"/>
    <bean  class="com.project.pojo.Dog"/>
	<!--byType: It will automatically find the object with the same property type as its own object in the container context bean! -->
 	<bean id="person" class="com.project.pojo.Person" autowire="byType">
        <property name="name" value="ADC"/>
    </bean>

Summary:

  • When Byname, it is necessary to ensure that the IDs of all beans are unique, and the bean needs to be consistent with the value of the automatically injected property set method
  • When Byname, you need to ensure that the class of all beans is unique, and the bean needs to be consistent with the attribute type automatically injected

7.4 automatic assembly using annotations

jdk1.5 support annotations, spring 2 5 supports annotation

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

To use notes:

1. Import constraints

2. Configure annotation support 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>

@Autowired

You can use it directly on the attribute! It can also be used in set mode!

Using Autowired, we don't need to write the Set method. The premise is that your automatic assembly is in the IOC (Spring) container and complies with byname

polular science:

@Nullable Field is marked with this annotation, indicating that this field can be null
public @interface Autowired {
	boolean required() default true;
}

Test code:

public class Person {
    //If the displayed definition of Autowired is false, it means that the object can be null. Otherwise, it cannot be empty
    @Autowired(required = false)
    private Cat cat;
    @Autowired
    private Dog dog;
    private String name;
}

If the environment of @ Autowired auto assembly is complex and the auto assembly cannot be completed through an annotation [@ Autowired], we can use * * @ Qualifier(value = "xxxx") * * to cooperate with @ Autowired and specify a unique bean object injection!

public class Person {
    //If the displayed definition of Autowired is false, it means that the object can be null. Otherwise, it cannot be empty
    @Autowired(required = false)
    private Cat cat;
    @Autowired
    @Qualifier(value ="dog22")
    private Dog dog;
    private String name;
}

@Resource annotation

public class Person {

   @Resource(name="cat2")
    private Cat cat;
    @Resource
    private Dog dog;
    private String name;
}

Summary

@Difference between Autowired and @ Resource:

  • They are used for automatic assembly and can be placed in the attribute field
  • @Autowired is implemented by byType, and this object must exist. If there are multiple objects of the same type, it can be implemented by byname
  • @Resource is implemented by byname. If the name cannot be found, it is implemented by byType
  • The execution order is different: @ Autowired is implemented by byType and @ Resource is implemented by byname.

8. Using annotation development

After using spring 4, to develop with annotations, you must ensure that the aop package is imported

To use annotations, you need to import context constraints and add annotation support!

  1. bean
  2. How are attributes injected
@Component
public class User {
    public String name;

    //Equivalent to < property name = "name" value = "ABC" / >
    @Value("abc")
    public void setName(String name) {
        this.name = name;
    }
}

3. Derived notes

@Cpont has several derived annotations. In our web development, we will layer according to the mvc three-tier structure!

  • dao[@Repository]

  • service[@Service]

  • controller[@Controller]

    The functions of these four annotations are the same. They all represent registering a class in Spring and assembling beans

4. Automatic assembly

- @Autowired:Auto assembly pass type-->name
- @Resource:Automatic assembly by name-->type
-  @Nullable Field is marked with this annotation, indicating that this field can be null

5. Scope

@Component
@Scope("prototype")
public class User {
    public String name;

    //Equivalent to < property name = "name" value = "ABC" / >
    @Value("abc")
    public void setName(String name) {
        this.name = name;
    }
}

6. Summary

xml and annotations:

  • xml is more versatile and suitable for any occasion! Simple and convenient maintenance
  • Annotations are not their own classes and cannot be used. Maintenance is relatively complex!

xml and annotation best practices:

  • xml is used to manage bean s;
  • Annotations are only responsible for completing attribute injection
  • In the process of using, we only need to pay attention to one problem: to make the annotation effective, we need to turn on the annotation support
    <!-- Specify the package to be scanned, and the annotations under the package will take effect automatically -->
    <context:component-scan base-package="com.project"/>
    <context:annotation-config/>

9. Configure Spring in Java

Now we don't use Spring's xml configuration at all, and leave it to java!

JavaConfig is a subproject of Spring. After Spring 4, it has become a core function

Entity class

//This annotation 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;
    }
    @Value("abc")//Attribute injection value
    public void setName(String name) {
        this.name = name;
    }

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

configuration file

//This will also be hosted by the Spring container and registered in the container, because it is originally a @ component,
//@Configuration means that this is a configuration class, just like the beans xml
@Configuration
@ComponentScan("com.project.pojo")
@Import(ProjectConfig2.class)
public class ProjectConfig {

    //Registering a bean is equivalent to writing a bean tag before
    //The name of this method is equivalent to the id attribute in the bean tag
    //The return value of this method is equivalent to the class attribute in the bean tag
    @Bean
    public User getUser(){
        return new User();//Is to return the object to be injected into the Bean
    }
}

Test class

public class MyTest {
    //If the configuration class method is completely used, we can only obtain the container through the Annotation context and load it through the class object of the configuration class
    @Test
    public void  test(){
        ApplicationContext context = new AnnotationConfigApplicationContext(ProjectConfig.class);
        User getUser = (User) context.getBean("getUser");
        System.out.println(getUser.getName());
    }
}

This pure Java configuration file can be seen everywhere in SpringBoot

10. Agent mode

Why learn agent mode? Because this is the bottom layer of spring AOP! [spring AOP and spring MVC]

Classification of agent mode:

  • Static proxy
  • Dynamic agent

10.1 static agent

Role analysis:

  • Abstract role: it is usually solved by using interfaces or abstract classes

  • Real role: the role represented

  • Agent role: represent the real role. After representing the real role, we usually do some ancillary operations

  • Customer: the person who accesses the proxy object!

Code steps:

  1. Interface
//Rent a house
public interface Rent {
    public void rent();
}

2. Real role

//landlord or landlady
public class Host implements Rent{
    @Override
    public void rent() {
        System.out.println("The landlord wants to rent the house");
    }
}

3. Agent role

public class Proxy implements Rent{
    private Host host;//Combination is better than inheritance

    public Proxy() {
    }

    public Proxy(Host host) {
        this.host = host;
    }

    @Override
    public void rent() {
        seeHouse();
        host.rent();
        contract();
        fee();
    }

    public void seeHouse(){
        System.out.println("The agent will show you the house");
    }
    public void contract(){
        System.out.println("Sign a lease contract");
    }
    public void fee(){
        System.out.println("Intermediary fee");
    }
}

4. Client access agent role

public class Client {
    public static void main(String[] args) {
        //The landlord wants to rent the house
        Host host = new Host();
        //Agents and intermediaries help landlords rent houses. Agent roles generally have some subsidiary operations
        Proxy proxy = new Proxy(host);
        //You don't have to face the landlord, just find an intermediary to rent a house
        proxy.rent();
    }
}

Benefits of agent mode:

  • The operation of real characters can be more pure! Don't pay attention to some public business
  • The public business is handed over to the agent role to realize the division of business
  • When the public business is expanded, it is convenient for centralized management

Disadvantages:

  • A real role will produce a proxy role; The amount of code will double and the development efficiency will be low

10.2 deepen understanding

Talk about AOP

10.3 dynamic agent

  • Dynamic agents have the same role as static agents
  • Dynamic proxy classes are dynamically generated, not written directly by us!
  • Dynamic agents are divided into two categories: interface based dynamic agents and class based dynamic agents
    • Interface based - JDK dynamic proxy [we use it here]
    • Class based: cglib
    • java bytecode implementation: javasist

Two classes need to be understood: Proxy generates a dynamic Proxy instance, and InnocationHandler calls the handler and returns a result

Benefits of dynamic agents:

  • The operation of real characters can be more pure! Don't pay attention to some public business
  • The public business is handed over to the agent role to realize the division of business
  • When the public business is expanded, it is convenient for centralized management
  • A dynamic proxy class is an interface, which is generally a corresponding type of business
  • A dynamic proxy class can proxy multiple classes as long as it implements the same interface

11,AOP

11.1 what is AOP

AOP (Aspect Oriented Programming) means: Aspect Oriented Programming, which realizes the unified maintenance of program functions through precompiled mode and runtime dynamic agent. AOP is the continuation of OOP, a hot spot in software development, an important content in Spring framework, and a derivative paradigm of functional programming. AOP can be used for all parts of business logic Isolation, so as to reduce the coupling between various parts of business logic, improve the reusability of programs, and improve the efficiency of development.

[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-aBbKGIs6-1639619572597)(C:\Users\ASUS\Pictures\Saved Pictures0)]

11.2 the role of AOP in Spring

Provide declarative transactions; Allows you to customize the cut plane

The following nouns need to be understood:

  • 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]
  • Advice: the work that must be done by the aspect. That is, it is a method in the class. [log method *]
  • Target: the notified object.
  • Proxy: an object created after notification is applied to the target object.
  • PointCut: the definition of the "place" where the aspect notification is executed.
  • Join point: the execution point that matches the pointcut.

In spring AOP, crosscutting logic is defined through Advice. Spring supports five types of Advice:

That is, Aop adds new functions without changing the original code

Using Spring to implement Aop

[key] to use AOP weaving, you need to import a dependency package!

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

The first way

Implemented through Spring API

First, write our business interface and implementation class

public interface UserService {

   public void add();

   public void delete();

   public void update();

   public void search();

}
public class UserServiceImpl implements UserService{

   @Override
   public void add() {
       System.out.println("Add user");
  }

   @Override
   public void delete() {
       System.out.println("delete user");
  }

   @Override
   public void update() {
       System.out.println("Update user");
  }

   @Override
   public void search() {
       System.out.println("Query user");
  }
}

Then write our enhancement class. We write two, one pre enhancement and one post enhancement

public class Log implements MethodBeforeAdvice {

   //Method: the method of the target object to execute
   //objects: parameters of the called method
   //Object: target object
   @Override
   public void before(Method method, Object[] objects, Object o) throwsThrowable {
       System.out.println( o.getClass().getName() + "of" + method.getName() +"Method was executed");
  }
}
public class AfterLog implements AfterReturningAdvice {
   //returnValue return value
   //Method called method
   //args parameter of the object of the called method
   //Target the called target object
   @Override
   public void afterReturning(Object returnValue, Method method, Object[]args, Object target) throws Throwable {
       System.out.println("Yes" + target.getClass().getName()
       +"of"+method.getName()+"method,"
       +"Return value:"+returnValue);
  }
}

Finally, register in the spring file and implement aop cut in implementation. Pay attention to import constraints

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

   <!--register bean-->
   <bean id="userService" class="com.kuang.service.UserServiceImpl"/>
   <bean id="log" class="com.kuang.log.Log"/>
   <bean id="afterLog" class="com.kuang.log.AfterLog"/>

   <!--aop Configuration of-->
   <aop:config>
       <!--breakthrough point expression:The expression matches the method to execute-->
       <aop:pointcut id="pointcut" expression="execution(* com.kuang.service.UserServiceImpl.*(..))"/>
       <!--Perform wrap; advice-ref Execution method . pointcut-ref breakthrough point-->
       <aop:advisor advice-ref="log" pointcut-ref="pointcut"/>
       <aop:advisor advice-ref="afterLog" pointcut-ref="pointcut"/>
   </aop:config>

</beans>

test

public class MyTest {
   @Test
   public void test(){
       ApplicationContext context = newClassPathXmlApplicationContext("beans.xml");
       UserService userService = (UserService) context.getBean("userService");
       userService.search();
  }
}

The importance of Aop: very important We must understand the ideas, mainly the understanding of ideas

Spring's Aop combines public business (logging, security, etc.) with domain business. When implementing domain business, public business will be added Realize the reuse of public business The domain business is more pure. The program ape focuses on the domain business, and its essence is dynamic agent

The second way

Custom classes to implement Aop

The target business class remains the same as userServiceImpl

Step 1: write our own cut in class

public class DiyPointcut {

   public void before(){
       System.out.println("---------Before method execution---------");
  }
   public void after(){
       System.out.println("---------After method execution---------");
  }
   
}

To configure in spring

<!--The second way is to customize the implementation-->
<!--register bean-->
<bean id="diy" class="com.kuang.config.DiyPointcut"/>

<!--aop Configuration of-->
<aop:config>
   <!--The second way: use AOP Label Implementation of-->
   <aop:aspect ref="diy">
       <aop:pointcut id="diyPonitcut" expression="execution(* com.kuang.service.UserServiceImpl.*(..))"/>
       <aop:before pointcut-ref="diyPonitcut" method="before"/>
       <aop:after pointcut-ref="diyPonitcut" method="after"/>
   </aop:aspect>
</aop:config>

Test:

public class MyTest {
   @Test
   public void test(){
       ApplicationContext context = newClassPathXmlApplicationContext("beans.xml");
       UserService userService = (UserService) context.getBean("userService");
       userService.add();
  }
}

The third way

Implementation using annotations

Step 1: write an enhanced class for annotation implementation

package com.kuang.config;

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
public class AnnotationPointcut {
   @Before("execution(* com.kuang.service.UserServiceImpl.*(..))")
   public void before(){
       System.out.println("---------Before method execution---------");
  }

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

   @Around("execution(* com.kuang.service.UserServiceImpl.*(..))")
   public void around(ProceedingJoinPoint jp) throws Throwable {
       System.out.println("Surround front");
       System.out.println("autograph:"+jp.getSignature());
       //Execute target method
       Object proceed = jp.proceed();
       System.out.println("After surround");
       System.out.println(proceed);
  }
}

Step 2: register the bean in the Spring configuration file and add the configuration supporting annotation

<!--The third way:Annotation implementation-->
<bean id="annotationPointcut"class="com.kuang.config.AnnotationPointcut"/>
<aop:aspectj-autoproxy/>

AOP: AspectJ AutoProxy: description

adopt aop Namespace<aop:aspectj-autoproxy />Declaration is automatically spring Which configurations are in the container@aspectJ Tangential bean Create a proxy and weave in the cut. of course, spring It is still used internally AnnotationAwareAspectJAutoProxyCreator The creation of automatic agent has been carried out, but the details of the specific implementation have been<aop:aspectj-autoproxy />It's hidden

<aop:aspectj-autoproxy />There is one proxy-target-class Property, default to false,Indicates use jdk Dynamic proxy weaving enhancement when configured as<aop:aspectj-autoproxy  poxy-target-class="true"/>When, it means to use CGLib Dynamic agent technology weaving enhancement. But even if proxy-target-class Set to false,If the target class does not declare an interface, then spring Will be used automatically CGLib Dynamic proxy.

12. Whole Mybatis

Steps:

1. Import relevant jar packages

  • junit
  • mybatis
  • mysql database
  • spring related
  • aop implantation
  • mybatis-spring[new ]

[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-6yda9kby-16396188771977) (Ping note. assets/image-20210411111712394.png)]

<dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.21</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.5</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.3.3</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.3.3</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.aspectj/aspectjweaver -->
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.9.6</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis-spring -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>2.0.6</version>
        </dependency>

    </dependencies>

2. Prepare configuration file

3. Test

12.1 recall Mybatis

1. Write entity class

2. Prepare core configuration file

3. Write interface

4. Write mapper xml

12.2 Spring-Mybatis

1. Write data source configuration

2.sqlSessionFactory

3.sqlSessionTemplate

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

      <!--DataSoucce:use Spring Data source replacement for Mybatis Configuration of c3p0 dbcp druid
      We use it here Spring Provided jdbc:jdbc.datasource.DriverManagerDataSource
      -->
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://localhost/mybatis?serverTimezone=UTC&amp;characterEncoding=utf8&amp;useUnicode=true&amp;useSSL=false"/>
        <property name="username" value="root"/>
        <property name="password" value="123456"/>
    </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"/>
        <!--It's OK. It's proved to be used Mybatis -->
        <property name="mapperLocations" value="classpath:com/project/mapper/*.xml"/>
     </bean>
    <!--sqlSessionTemplate -->
    <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
        <!--Only constructor injection can be used sqlSessionFactory,Because it doesn't set method-->
        <constructor-arg index="0" ref="sqlSessionFactory"/>
    </bean>


</beans>

4. You need to add an implementation class to the interface

  • Mode 1
public class UserMapperImpl implements UserMapper {

    //All our operations are executed using sqlSession. In the past, sqlSessionTemplate is used now
    private SqlSessionTemplate sqlSession;

    public void setSqlSession(SqlSessionTemplate sqlSession) {
        this.sqlSession = sqlSession;
    }

    @Override
    public List<User> getUserList() {
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        return mapper.getUserList();
    }
}
  • Mode II
public class UserMapperImpl2 extends SqlSessionDaoSupport implements UserMapper {

    @Override
    public List<User> getUserList() {
        return getSqlSession().getMapper(UserMapper.class).getUserList();
    }
}

5. Inject the implementation class written by yourself into Spring

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

    <import resource="spring-dao.xml"/>
    <bean id="userMapper" class="com.project.mapper.UserMapperImpl">
        <property name="sqlSession" ref="sqlSession"/>
    </bean>

    <bean id="userMapper2" class="com.project.mapper.UserMapperImpl2">
        <property name="sqlSessionFactory" ref="sqlSessionFactory"/>
    </bean>
</beans>

6. Test results

    @Test
    public void test3() {
        ApplicationContext context = new ClassPathXmlApplicationContext("spring-dao.xml");
        UserMapper userMapper = context.getBean("userMapper", UserMapper.class);
        for (User user : userMapper.getUserList()) {
            System.out.println(user);
        }
    }

13. Declarative transaction

1. Review transactions

  • Treat a group of businesses as a business, either all succeed or all fail
  • Transaction is very important in project development. Data consistency should not be carelessly designed
  • Ensure integrity and consistency

Transaction ACID principle:

  • Atomicity
  • uniformity
  • Isolation
    • Multiple businesses may operate the same resource to prevent data corruption
  • persistence
    • Once the transaction is committed, no matter what happens to the system, the result will not be affected and will be persisted to the memory

2. Transaction management in spring

  • Declarative transaction: AOP
  • Programming transactions: need to be done in code

Thinking: why do you need affairs?

  • If the transaction is not configured, there may be inconsistent data submission
  • If we do not configure declarative transactions in spring, we need to manually configure transactions in the code
  • Transaction is very important in the development of the project. It involves the consistency and integrity of data, which should not be careless

Notes:

  • @Autowired: auto assembly type – > name
  • @Resource: auto assembly name – > type
  • @The Nullable field marks this annotation, indicating that this field can be null
  • Comptent: component, placed on a class, indicating that this class is managed by Spting, that is, bean

Topics: Java Spring Spring Boot Back-end