Spring super comprehensive detailed explanation

spring overview

Spring is a lightweight, non-intrusive IOC and AOP one-stop Java development framework that emerged in 2003
  to simplify enterprise-level application development.
1. Lightweight: It means that the jar package of spring core functions is not large
2. Non-intrusive: Our business code does not need to inherit or implement any class or interface in spring
3.IOC: Inversion of Control is to invert the right to create objects to the spring framework
4. AOP: Aspect-Oriented Programming It is a programming idea and a supplement to Object-Oriented Programming (OOP). Object-oriented programming abstracts the program into objects at various levels, while aspect-oriented programming abstracts the program into various aspects
5. One-stop framework: Spring itself also provides data access functions and web functions, and can manage other frameworks well

Spring Architecture

Core Container (core container):
Beans: Manage Beans
Core: The core of Spring, which provides the creation of IOC container objects and handles dependent object relationships
Context: The configuration file is a collection of Bean relationships, also called an IOC container, which calls most of the methods in spring-core
ExpressionLanguage: SpEL expression
AOP: Aspect programming    enables Spring framework management objects to support AOP, and this module also provides transaction management
ORM: Provides support for existing ORM frameworks, such as Hibernate, JDO, Mybatis, etc.
DAO: Provides support for the Data Access Object (DAO) pattern and JDBC, and separates the code for implementing business logic and database access.
Data Access (database integration): JDBC, ORM, OXM, JMS, Transaction
springWeb (MVC Web development):   It is a module of the spring framework. SpringWeb and spring do not need to be integrated through the middle integration layer. It is an MVC-based web framework, which facilitates the transmission of front-end and back-end data. It has a controller, receives external requests, and parses parameters to the service layer

spring build and test

The construction of the spring project is to add some dependencies and configure some configurations on the basis of the Maven project

1. Maven imports spring core foundation jar

<!-- spring-context -->
< dependency >
< groupId >org.springframework</ groupId >
< artifactId >spring-context</ artifactId >
< version >5.2.2.RELEASE</ version >
</ dependency >
2. Write the spring configuration file
<? xml version ="1.0" encoding ="UTF-8" ?>
< beans xmlns ="http://www.springframework.org/schema/beans"
xmlns: xsi ="http://www.w3.org/2001/XMLSchema-instance"
xsi :schemaLocation ="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd" >
< bean id ="admin" class ="com.ffyc.spring.bean.Admin" > </ bean >
</ beans >
3. Write an Admin entity class
public class Admin {
    private int id;
    private String account;

    public Admin() {
        System.out.println("无参构造方法");
    }

    public Admin(int id, String account) {
        this.id = id;
        this.account = account;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getAccount() {
        return account;
    }

    public void setAccount(String account) {
        this.account = account;
    }

    @Override
    public String toString() {
        return "Admin{" +
                "id=" + id +
                ", account='" + account + '\'' +
                '}';
    }
}

4. Test

 //读取spring配置文件,并对文件中配置的对象进行创建
        ClassPathXmlApplicationContext app = new ClassPathXmlApplicationContext("spring.xml");
                                       Admin admin = app.getBean("admin", Admin.class);
        System.out.println(admin);

IOC (Inversion of Control)

Overview:  It is a design idea , which is to hand over the control of manually creating objects in the program to the Spring framework.
manage. The IOC container is a container with a dependency injection function. It is responsible for the instantiation of objects, the initialization of objects, the configuration of dependencies between objects and objects, the destruction of objects, and the search for externally provided objects. The entire life cycle of objects is controlled by the container. to control. The objects we need to use are all managed by the ioc container. We don’t need to manually create objects through new. The ioc container will help us assemble them directly. When we need to use them, we can directly obtain them from the ioc container. up.
Positive control: If you want to use an object, you need to be responsible for the creation of the object yourself
Anti-control: If you want to use an object, you only need to obtain the object you need to use from the Spring container, and don't care about the object creation process, that is, the control of creating the object is reversed to the Spring framework.
The underlying implementation method: parsing xml/scanning annotation tags + factory mode + reflection mechanism

Bean management in spring

1. Dependency injection based on xml configuration

When creating objects in spring (inversion of control), we also need to initialize and assign values ​​​​to our object properties. This process is called dependency injection.

(1) get, set injection

 <bean id="admin" name="admin2" class="com.ffyc.ssm.model.Admin" scope="prototype">
           <property name="id" value="10"></property>
           <property name="account" value="admin"></property>
         
 </bean>     
	

(2) Construction method injection

  <bean id="admin" name="admin1" class="com.ffyc.ssm.model.Admin" scope="prototype">
            <constructor-arg name="id" value="100"></constructor-arg>
            <constructor-arg name="account" value="admins"></constructor-arg>
  </bean>
Bean configuration requires spring-managed classes, also called spring-managed classes called bean objects
id generated object name
class full class name
name Object alias, can be multiple
scope (bean scope): singleton (default value): There is only one bean instance in Spring, singleton mode. It will be created when spring starts
prototype: prototype getBean() will be new Bean()
2. Annotation way to achieve dependency injection
(1) The jar package required for annotation, the annotation function is encapsulated in the AOP package, just import the Spring aop jar package
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-aspects</artifactId>
    <version>5.2.2.RELEASE</version>
</dependency>

(2) Turn on annotation scanning in spring

<context:component-scan base-package="包名"> </context:component-scan>
(3) Create objects using annotations
@Component(value="admin") is equivalent to <bean id="admin" class=""></bean>
@Service
@Repository
All the above annotations can realize the function of creating objects, but for the subsequent extension of functions, different annotation marks are used in different layers
@Scope(value="prototype") prototype @Scope(value="singleton") singleton
3. Annotation method injection property
(1)@Autowired
@Autowired is an annotation provided by Spring, and there are two ways to inject it
byType automatic injection
This annotation uses the way of autowiring beans by type by default.
byName automatically injected
If we want to assemble by name, we can use it in conjunction with the @Qualifier annotation.
The annotations @Autowired and @Qualifier need to be used jointly on the reference property. The value attribute of @Qualifier is used to specify the id value of the bean to be matched.
  @Autowired 
    @Qualifier(value = "adminDao")
    AdminDao adminDao;
(2) @Resource automatic injection
Spring provides support for @Resource annotation in jdk.
The @Resource annotation can match beans both by name and by type. By default, it is automatically injected by ByType
byName injects reference type properties
The @Resource annotation specifies its name attribute, and the value of name is the id of the Bean to be matched according to the name.
 @Resource(name = "adminDao")
    AdminDao adminDao;

4. Comparison of annotations and XML

Annotation advantages: convenient, intuitive, and efficient (less code, not as complicated as writing configuration files)
Disadvantages of annotation: It is written into the Java code in a hard-coded manner, and the modification requires recompilation of the code.
The advantages of xml are: configuration and code are separated, and modifications are made in xml without compiling the code, and the new configuration can be loaded by restarting the server.
The disadvantages of xml are: troublesome writing, low efficiency, and large projects are too complicated.

Spring JDBC

Spring is a one-stop framework: Spring itself also provides SpringMVC for the control layer and Spring JdbcTemplate for the persistence layer.
Build steps:
1. Download the jar package of Spring JdbcTemplate
<!-- spring-jdbc -->
< dependency >
< groupId >org.springframework</ groupId >
< artifactId >spring-jdbc</ artifactId >
< version >5.2.2.RELEASE</ version >
</ dependency >
2. Import the data source management component druid provided by Alibaba   
Commonly used database connection pool components: dbcp c3p0 data source component, which encapsulates the connection database and the database connection pool function
<!-- Ali data source -->
< dependency >
< groupId >com.alibaba</ groupId >
< artifactId >druid</ artifactId >
< version >1.1.10</ version >
</ dependency >
3. Import properties file ( config.properties )
classDriverName=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://127.0.0.1:3306/ssmdb?serverTimezone=Asia/Shanghai
uname=root
pwd=root
<context:property-placeholder location="config.properties"/>
4. Manage data source objects
Spring management and database link (data source)
 
<bean id="dataSource"class="com.alibaba.druid.pool.DruidDataSource">
<propertyname="driverClassName" value="${driverClassName}"></property>
<property name="url" value="${url}"></property>
<property name="username" value="${uname}"></property>
<property name="password" value="${pwd}"></property>
<property name="initialSize" value="10"></property>
<property name="minIdle" value="5"></property>
<property name="maxActive" value="20"></property>
</bean>
5. Create a spring-encapsulated jdbc
 <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <!--注入数据源的对象-->
        <property name="dataSource" ref="dataSource"></property>
    </bean>

6. Obtain the JdbcTemplate object in the class and use it directly.

 

 

AOP (Aspect Oriented Programming)

Preface:      After developing a version, if you need to add new functions later, you need to modify the original code and add codes that call new functions. In this way, development is very troublesome, and there will be a lot of redundant code.

Overview:   AOP is the abbreviation of Aspect Oriented Programming. It is a continuation of OOP, which can isolate business logic and non-business logic, thereby reducing the coupling between parts, improving program reusability, and improving development efficiency. AOP and OOP are two design ideas for different fields. OOP (Object-Oriented Programming) abstracts and encapsulates entities and their attributes and behaviors in the business process to obtain clearer and more efficient division of logical units. AOP, on the other hand, extracts aspects in the business processing process. It faces a certain step or stage in the processing process, so as to obtain the isolation effect of low coupling between various parts in the logic process.

That is to extract some non-business codes in the program, and add additional functions to the program without modifying the original code. Non-business
codes:   (verify permissions, print logs, submit transactions, and unify exception handling)

Core principle: Use dynamic proxy to add relevant logic before and after the method is executed or when an exception occurs.

Use case: transaction processing: open a transaction, close a transaction, roll back a transaction after an exception occurs
                Judgment of authority: Before executing the method, determine whether it has authority
                Log: log processing before execution

 Basic concepts of AOP

Joinpoint: A method in a class that can be enhanced, this method is called a joinpoint
Pointcut: There are many methods in the class that can be enhanced, but in fact only add and update are enhanced, then the add and update methods are called pointcuts (actually implemented connection points)
Advice: Advice refers to what an aspect needs to do at a specific connection point (enhanced functionality). Notifications are divided into pre-method execution notifications, post-method execution notifications, surrounding notifications, etc.
Aspect: The whole process of adding advice to a pointcut is called an aspect.
Target (Target): The target object of the agent (joint point, class where the entry point is located)
Proxy (Proxy): The proxy object created when the notification is applied to the target object
Spring AOP implementation
AspectJ is an AOP framework based on the Java language. It provides powerful AOP functions, and its implementation is simpler and easier to use, and it also supports annotation development. Therefore, Spring has also introduced AspectJ's implementation of AOP into its own framework.
First download the AOP related jar
< dependency >
< groupId >org.springframework</ groupId >
< artifactId >spring-aspects</ artifactId >
< version >5.2.2.RELEASE</ version >
</ dependency >
1. Implementation based on aspectj's xml configuration method
There are five types of advice commonly used in AspectJ:
Pre-Notification, Post-Notification, Surrounding Notification, Exception Notification, Final Notification
< bean id ="aopdemo" class ="com.ff.spring.aop.AopDemo" ></ bean >
< aop :config >
<!-- Configuration entry point -->
< aop :pointcut expression ="execution(*com.ff.spring.service.UserService.adduser(..))" id ="adduser" />
< aop :pointcut expression ="execution(*com.ff.spring.service.UserService.*(..))" id ="allmethod" />
<!-- Configure notifications and entry points -->
< aop :aspect ref ="aopdemo" >
< aop :before method ="savelog" pointcut-ref ="adduser" />
< aop :after method ="savelog" pointcut-ref ="adduser" />
< aop :around method ="aroundAdvice" pointcut-ref ="adduser" />
< aop :after-throwing method ="exceptionAdvice" pointcut-ref ="allmethod"  throwing ="e" />
</ aop :aspect >
</ aop :config >

 

2. Realization based on annotation
Start AspectJ support: <aop:aspectj-autoproxy /> <!--autoproxy-->

 

Surrounding notifications can include all preceding notifications with

Spring transaction management

Overview:    Things can be seen as a unit consisting of several operations on the database.
When we develop enterprise applications, an operation for business personnel is actually a combination of multi-step operations for reading and writing data. During the sequential execution of data operations, exceptions may occur in any step of the operation, and the exceptions will cause subsequent operations to fail. At this time, because the business logic has not been completed correctly, the previous successful operation of the data is not reliable. fallback in this case.
The role of the transaction is to ensure that every operation of the user is reliable. Every step of the operation in the transaction must be successfully executed. As long as there is an exception, it will fall back to the state where the transaction was not operated at the beginning. These operations are either completed or are canceled to ensure that the data meets the consistency requirements
Transaction management in Spring is divided into two forms, one is programmatic transaction and the other is declarative transaction.
Programmatic transactions are rarely used in projects. This method needs to inject a transaction management pair TransactionTemplate, and then write code implementation when we need to commit or rollback transactions in our code.
Declarative transaction management is based on AOP, the essence is to intercept the method before and after, so the declarative transaction is at the method level.
There are two ways of Spring declarative transaction management:
xml-based configuration
Implementation based on annotation
Implementation based on annotation
1. Configure the transaction manager
<!-- Configure the spring transaction management class and inject the data source -->
< bean id ="transactionManager"
class ="org.springframework.jdbc.datasource.DataSourceTransactionManager" >
< property name ="dataSource" ref ="dataSource" ></ property >
</ bean >
2. Enable annotation transaction management 
< tx :annotation-driven transaction-manager ="transactionManager" />
3. Control transactions in service
@Service(value="adminDao")
@Transactional
Usage of @Transactional

        Generally, the @Transactional tag is added to the service.
        @Transactional can be added to the class in the service layer. All methods in the class will add transaction management functions.
        If @Transactional is only added to a certain method, it means that this method is in transaction management. conduct

@Transactional will fail in the following 6 cases.
         1. Modify a non-public method, the underlying permissions are only for public modified methods
         2. The exception in the method is caught and processed by catch
         3. By default, a compile-time exception occurs, and the transaction Not valid
            By default, only run-time exceptions are captured @Transactional(rollbackFor = RuntimeException.class)
            We can modify it to @Transactional(rollbackFor = Exception.class), so that any exception can be handled
         4. @Transactional transaction propagation Behavior setting error
         5. The database engine does not support transactions. The database engine is a specific data processing implementation mechanism at the bottom of mysql.
             Two engines commonly used: innodb (supports transaction functions), myisam (does not support transactions)
         6. In a non-transaction Use this in the method (original object == new object)     

Spring transaction propagation behavior

Overview: Since it is communication, there must be at least two things before communication can occur. The behavior of propagation does not exist in monomers. Transaction propagation behavior (propagation behavior) refers to how a transaction method should behave when it is called by another transaction method. The transaction propagation behavior is a unique transaction enhancement feature of the Spring framework, which does not belong to the actual provider database behavior of the transaction

Spring defines seven propagation behaviors:
PROPAGATION_REQUIRED If there is no transaction currently, create a new transaction, if there is already a transaction, join this transaction. This is the most common choice.
PROPAGATION_SUPPORTS supports the current transaction. If there is no current transaction, it will be executed in a non-transactional manner.
PROPAGATION_MANDATORY uses the current transaction, or throws an exception if there is no current transaction.
PROPAGATION_REQUIRES_NEW Create a new transaction, if there is a current transaction, suspend the current transaction.
PROPAGATION_NOT_SUPPORTED performs operations in a non-transactional manner. If there is a current transaction, suspend the current transaction.
PROPAGATION_NEVER executes in a non-transactional manner, throwing an exception if a transaction currently exists.
PROPAGATION_NESTED Executes within a nested transaction if a transaction currently exists. If there is no current transaction, perform a similar operation to PROPAGATION_REQUIRED.

Spring integrates Mybatis

The core of Spring's integration of Mybatis is to hand over SqlSessionFactory to Spring and manage it by
Spring manages the proxy implementation of the dao interface
1. Import mybatis jar package
Spring combined with mybatis plugin package
< dependency >
< groupId >org.mybatis</ groupId >
< artifactId >mybatis-spring</ artifactId >
< version >1.3.1</ version >
</ dependency >
2. Configure sqlSessionFactory
< bean id ="sqlSessionFactory" class ="org.mybatis.spring.SqlSessionFactoryBean" >
< property name ="dataSource" ref ="dataSource" ></ property >
< property name ="configLocation" value ="mybatis-config.xml" ></ property >
< property name ="mapperLocations" value ="com/ff/*Mapper.xml" >
</ property >
</ bean >
3. Specify the generation interface proxy
< bean id ="mapperFactory" class ="org.mybatis.spring.mapper.MapperScannerConfigurer" >
< property name ="basePackage" value ="com.ff.ssm.dao" ></ property >
< property name ="sqlSessionFactoryBeanName" value ="sqlSessionFactory" >
</ property >
</ bean >
4. Inject the Dao proxy interface in the service, which is implemented by the Spring proxy
@Resource
LoginDao loginDao;

Guess you like

Origin blog.csdn.net/weixin_71243923/article/details/128267166