Spring 5 learning notes (full version)

1,Spring

1.1 INTRODUCTION

  • Spring: Spring ------ > spring brought to the software industry!

  • Spring concept: it makes the existing technology easier to use. It is a hodgepodge and integrates the existing technology framework

  • SSM:SpringMvc+Spring+MyBatis

  • Official website: https://spring.io/projects/spring-framework#overview

  • Official download address: https://docs.spring.io/spring-framework/docs/4.3.9.RELEASE/spring-framework-reference/

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

1.2 advantages

  • Spring is an open source free framework (container)!
  • Spring is a lightweight, non intrusive framework!
  • Control flip (IOC), aspect oriented programming (AOP)!
  • Support transaction processing and framework integration!

To sum up: Spring is a lightweight control flip (IOC) and aspect oriented programming (AOP) framework!

IOC theoretical derivation

  1. UserDao interface
  2. UserDaoImpl implementation class
  3. UserService business interface
  4. UserServiceImpl business implementation

IOC essence

Control reversal 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. For programs without IODC, we use object-oriented programming. The creation of objects and the dependencies between objects are completely hard coded in the program. The creation of objects is controlled by the program itself. After control inversion, the objects are transferred to a third party. Personally, I think the so-called control inversion is: gain The way we depend on objects is reversed.

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 self injection.

How IOC creates objects

1. Create objects using parameterless construction, default

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

1. Subscript assignment

2. Type

3. Parameter name

Spring configuration

alias

If you have created an alias, you can also create objects through the alias

<alias name = "user" value = "userNew"></alias>

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

import

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

Dependency injection

Constructor Injection

set mode injection

Dependency injection: Set injection!

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

Other ways

We can use p namespace and c namespace injection

<?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-->
    <bean id="user" class="com.kuang.pojo.User" p:name="dark gray" p:age="18"></bean>
    <!--c Namespace injection through constructor-->
    <bean id ="user2" class="com.kuang.pojo.User" c:age="19" c:name="Bingbing"></bean>
</beans>

Note: the p naming and c namespace 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"

Scope of the bean

[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-nscnan0z-1628051079810) (C: \ users \ Wang \ appdata \ roaming \ typora \ typora user images \ image-202108012055140. PNG)]

1. Singleton mode (default mode)

    <bean id ="user2" class="com.kuang.pojo.User" c:age="19" c:name="Bingbing" scope="singleton"></bean>

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

    <bean id ="user2" class="com.kuang.pojo.User" c:age="19" c:name="Bingbing" scope="prototype"></bean>

3. The remaining request session application s can only be used in web development!

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

  • Display configuration in xml

  • Display configuration in java

  • Implicit automatic assembly bean [important]

    • byName

         <!--
              byName:It will automatically insert objects and its own objects in the container context set Method beanid
              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.kuang.pojo.Person" autowire="byName">
              <property name="name" value="dark gray"></property>
          </bean>
      

      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 set method of the automatically injected attribute

      When bytype, you need to ensure that the class of all beans is unique, and the bean needs to be consistent with the type of automatically injected attributes

Annotation for automatic assembly

jdk1.5 began to support annotations, spring 2 5 start supporting annotations

Enable annotation support
<context:annotation-config/>

Notes for use:

1. Import context constraint

2. Configuration annotation support

@Autowired

It can be used directly on attributes or set methods

Using Autowired, we don't need to write the Set method, provided that your auto assembled attribute exists in the IOC (Spring) container and conforms to the name byname!

popularization of science

@Nullable Field is marked with this annotation, indicating that this field can be null

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

@Difference between Resource and @ Autowired:

  • They are automatically assembled and can be placed on the attribute field
  • @Autowired is implemented by byType, and this object must exist!
  • @Resource is implemented by byname. If the name cannot be found, it is implemented by ByType. If both cannot be found, an error is reported
  • The execution order is different: @ Autowired is implemented by byType and @ Resource is implemented by byname

Using annotation development

After 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

@Component: the component is placed on the class, indicating that the class is managed by spring

1,bean

2. How are attributes injected

package com.kuang.pojo;

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

@Component
public class User {
    @Value("dark gray")
    public String name;
}

3. Derived annotation

@Component has several derived annotations. We will layer according to MVC three-tier architecture in web development

  • dao[@Repository]
  • service[@Service]
  • controller[@Controller]

This is an annotation. The functions are the same. They all represent registering a class in Spring and assembling beans

4. Automatic assembly

5. Scope @ scope

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
  • Best practices for xml and annotations:
    • 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. If we must make the annotation effective, we need to turn on the annotation support

Configure spring in java

Now we will not use the xml configuration of Spring at all, and leave it to Java

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

package com.kuang.pojo;

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

//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;
    }
    @Value("dark gray")
    public void setName(String name) {
        this.name = name;
    }

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

package com.kuang.config;

import com.kuang.pojo.User;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@Configuration //This will also be managed by the Spring container and registered in the container, because it is a @ Component
// @Configuration indicates that this is a configuration class,
@ComponentScan("com.kuang.pojo")
public class KuangConfig {
//    Registering a bean is equivalent to a bean tag we wrote earlier
//    This method
    @Bean
    public User getUser(){
        return new User();
    }
}

import com.kuang.config.KuangConfig;
import com.kuang.pojo.User;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class MyTest {
    public static void main(String[] args) {
        ApplicationContext context = new AnnotationConfigApplicationContext(KuangConfig.class);
        User user = (User) context.getBean("getUser");
        System.out.println(user.getName());
    }
}

proxy pattern

Classification of agent mode:

  • Static proxy
  • Dynamic agent

Static proxy

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
  • Client: the person who accesses the proxy object

Code steps:

  • Interface
  • Real role
  • delegable role
  • Client access agent role

Benefits of agent mode:

  • It can make the operation of real characters more pure
  • The public business is handed over to the agent role
  • 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 ~ the development efficiency will be lower

Dynamic agent

  • Dynamic agents have the same role as static agents
  • The proxy class of dynamic proxy is generated dynamically, which is not written directly
  • Dynamic agents are divided into two categories: interface based dynamic agents and class based dynamic agents
    • Interface based JDK dynamic agent
    • Based on class - cglib
    • java bytecode implementation: javasist

You need to know two classes: Proxy: Proxy and InvocationHandler: the program that invokes the handler

InvocationHandler

package com.kuang.demo4;

import com.kuang.demo03.Rent;

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

//We will use this class to automatically generate proxies
public class ProxyInvocationHandler implements InvocationHandler {
    /*Proxy interface*/
    private Object target;

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

    //    Generated proxy class
    public Object getProxy(){
        return Proxy.newProxyInstance(this.getClass().getClassLoader(),target.getClass().getInterfaces(),this);
    }
    /*Process the proxy instance and return the result*/
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        log(method.getName());
        //        The essence of dynamic agent is to use reflection mechanism
        Object result = method.invoke(target, args);
        return result;
    }
    public void log(String msg){
        System.out.println("Yes"+msg+"method");
    }
}

Benefits of dynamic agents

  • It can make the operation of real roles more pure without paying attention to some public businesses
  • The public will be handed over to the agent role! The division of business is realized
  • When public business is expanded, it is convenient for centralized management!
  • A dynamic agent class represents 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.

The role of AOP in Spring

Provide declarative statements; Allows you to customize the cut plane

  • Crosscutting concerns: methods or functions that span multiple modules of an application. That is, the parts that have nothing to do with our business logic, but we need to focus on are crosscutting concerns, such as logging, security, caching, transactions, etc
  • ASPECT: a special object whose crosscutting concerns are modularized. That is, it is a class
  • Advice: the work that must be done in the aspect. That is, it is a method in the class
  • Target: notified object
  • Proxy: the object created after the notification is applied to the target object
  • Entry point: (PointCut): definition of the "place" where the aspect notification is executed
  • Join point: the execution point that matches the pointcut

Method 1: use Spring API interface [mainly implemented by Spring API interface]

Method 2: Customize to implement [mainly section]

Method 3: using annotations

Integrate Mybatis

Steps:

1. Import related jar packages

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

2. Write configuration file

3. Testing

Recall mybatis

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

Mybatis-Spring

  1. Write data source configuration
  2. sqlSessionFactory
  3. sqlSessionTemplate
  4. You need to add an implementation class to the interface
  5. Inject the implementation class written by yourself into Spring
  6. Test and use!

Declarative transaction

1. Review transactions

  • Treat a group of business as a business; Either all succeed or all fail!
  • Transaction is very important in project development. The consistency of design data should not be careless
  • Ensure integrity and consistency

ACID principles for transactions

  • Atomicity
  • uniformity
  • Isolation: multiple businesses may operate the same resource to prevent data corruption
  • Persistence: once a transaction is committed, no matter what happens to the system, the results will not be affected and will be written to the memory persistently

Things Management in Spring

  • Declarative transaction: AOP
  • Programming transactions: it is necessary to write code again to manage transactions

Why transactions are needed?

  • If transactions are not allocated, there may be inconsistent data submission
  • If we no longer configure declarative transactions in Spring, we need to manually configure transactions in our code
  1. Write mapper xml
  2. test

Mybatis-Spring

  1. Write data source configuration
  2. sqlSessionFactory
  3. sqlSessionTemplate
  4. You need to add an implementation class to the interface
  5. Inject the implementation class written by yourself into Spring
  6. Test and use!

Declarative transaction

1. Review transactions

  • Treat a group of business as a business; Either all succeed or all fail!
  • Transaction is very important in project development. The consistency of design data should not be careless
  • Ensure integrity and consistency

ACID principles for transactions

  • Atomicity
  • uniformity
  • Isolation: multiple businesses may operate the same resource to prevent data corruption
  • Persistence: once a transaction is committed, no matter what happens to the system, the results will not be affected and will be written to the memory persistently

Things Management in Spring

  • Declarative transaction: AOP
  • Programming transactions: it is necessary to write code again to manage transactions

Why transactions are needed?

  • If transactions are not allocated, there may be inconsistent data submission
  • If we no longer configure declarative transactions in Spring, we need to manually configure transactions in our code
  • Transaction is very important in the development of the project. The consistency and integrity of data should not be sloppy.

Keywords: Java Spring SSM

Added by Biocide on Thu, 30 Dec 2021 20:46:21 +0200