Spring framework learning

Time:2021-7-30

Advantages of spring

  • Spring is an open source and free framework
  • Spring is a lightweight, non intrusive framework
  • Inversion of control (IOC), aspect oriented programming (AOP)
  • Support transaction processing and framework integration

Spring is a lightweight inversion of control (IOC), aspect oriented programming (AOP) framework

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 term of 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.
Inversion of control is a way to produce or obtain specific objects through description (XML or annotation) and through a third party. In spring, the LOC container implements control inversion, and its implementation method is dependency injection (DL).

Dependency injection

Construct its injection

Set injection

Automatic assembly of beans

ByName

ByType

Using annotations

proxy pattern

AOP

What is AOP

AOP (aspect oriented programming) is a design idea and aspect oriented programming in the field of software design. It is a supplement and perfection of object-oriented programming (OOP). It is a technology that adds additional functions to the program dynamically and uniformly without modifying the source code through precompiling and runtime dynamic agent.

AOP application scenario

AOP is to dynamically add some extended functions based on OCP (opening and closing principle) without changing the core business code of the original system, and can “control” the execution of objects. For example, AOP is applied to log processing, transaction processing, permission processing, cache processing and so on.
Spring framework learning

AOP related terms

  • Aspect:The cross section object is generally a concrete class object (which can be declared with the help of @ aspect).
  • Advice:Actions (extended functions) performed on a specific connection point of the section, such as around, before, after, etc.
  • Join point:A specific point in the process of program execution, generally refers to the method intercepted.
  • Pointcut:A definition of multiple join points, which can generally be understood as a collection of multiple join points.

AOP introduction practice

Based on the core business of the project, add simple log operations, and output the execution time of the target method with the help of slf4j log API.
Add dependency:

<dependency>
       <groupId>org.springframework.boot</groupId>
       <artifactId>spring-boot-starter-aop</artifactId>
</dependency>

To create a log slice object:
This log aspect class is used as a core business enhancement (a cross-sectional object) class to output the business execution time. Its key codes are as follows:

@Aspect
@Slf4j
@Component
public class SysLogAspect {
         @Pointcut("bean(sysUserServiceImpl)")
         public void logPointCut() {}

         @Around("logPointCut()")
         public Object around(ProceedingJoinPoint jp)
         throws Throwable{
                 try {
                   log.info("start:{}"+System.currentTimeMillis());
                   Object result=jp.proceed();// The target method will eventually be called
                   log.info("after:{}"+System.currentTimeMillis());
                   return result;
                 }catch(Throwable e) {
                   log.error("after:{}",e.getMessage());
                   throw e;
                 }
         }
}

explain:

  • @The aspect annotation is used to identify or describe the facet type in AOP. The object built based on the facet type is used to extend the function of the target object or control the execution of the target object.
  • @The pointcut annotation is used to describe the methods in the aspect and define the pointcut in the aspect (described based on a specific expression). In this case, the pointcut expression uses a bean expression, which starts with a bean, and the content in bean brackets is the name of a bean object managed by spring.
  • @The around annotation is used to describe the method in the aspect. Such a method will be considered as a surround notification (an action to be executed before and after the execution of the core business method),@The value of the value attribute inside the aournd annotation is a pointcut expression or a reference to the pointcut expression (this reference is the method name of the method described by a @ pointcut annotation).
  • The proceedingjoinpoint class is a join point type. This type of object is used to encapsulate some information about the target method to be executed.Can only be used for method parameters described by the @ around annotation

Test:

@SpringBootTest
public class AopTests {
         @Autowired
         private SysUserService userService;
         @Test
         public void testSysUserService() {
                 PageObject<SysUserDeptVo> po=
                 userService.findPageObjects("admin",1);
                 System.out.println("rowCount:"+po.getRowCount());
         }
}

AOP principle analysis

  • Implementation based on JDK proxy:

If the target object has an implementation interface, you can create a proxy object for the target object based on JDK, and then extend the function for the target object, as shown in the figure:
Spring framework learning

  • Based on cglib proxy:

If the target object does not implement the interface (of course, it is possible to implement the interface), the function extension can be woven for the target object based on cglib proxy, as shown in the figure:
Spring framework learning

Advanced AOP programming

Notification type

  • @Before
  • @AfterReturning
  • @AfterThrowing
  • @After
  • @Around key points(highest priority)

Note: it is up to the business to decide what notifications to use in the aspect class. It does not mean that all notifications should be written in the aspect class.

Execution order of notification

If all these notifications are written to a section object, the execution sequence and process are as follows:
Spring framework learning
Note: the @ afterthrowing notification can only be executed when an exception occurs, so it can be implemented in this method when some exceptions are monitored. In the actual project, you may not define all notifications in the aspect, but specifically define which notifications should be implemented in combination with the business.

Pointcut expression

In spring, specific pointcuts are defined by pointcut expressions. The definitions and descriptions of common AOP pointcut expressions are as follows:

Indicator effect
bean All methods used to match the specified bean object
within Used to match all methods in all classes under the specified package
execution Used to match specific methods according to specified syntax rules
@Annotation The method used to match the specified annotation modifier
  • Bean expressions are generally applied at the class level to achieve coarse-grained pointcut definitions
Bean ("userserviceimpl") specifies all methods in a userserviceimpl class.
   Bbean ("* serviceimpl") specifies all methods in all classes with the suffix serviceimpl.

Note: the object inside the bean expression is a bean object managed by the spring container. The name inside the expression should be the name of a bean in the spring container.

  • @Annotation expressions are applied at the method level to achieve fine-grained pointcut expression definitions
@Annotation (COM. Cy. PJ. Common. Annotation. Requiredlog) matches the method described by this annotation.
@Annotation (COM. Cy. PJ. Common. Annotation. Requiredcache) matches the method described by this annotation.

Among them: requiredlog is the annotation defined by ourselves. When we use @ requiredlog annotation to modify the business layer method, the system bottom layer will perform daily extension operation when executing this method.

  • Within expression (understand)

Within expression is applied to class level to realize coarse-grained definition of pointcut expression. Case analysis:

  • Within (“AOP. Service. Userserviceimpl”) specifies all methods inside this class in the current package.
  • Within (“AOP. Service. *”) specifies all methods of all classes in the current directory.
  • All methods specified in the current directory (“aohin. Service *”) and all subdirectories.

Within expression application scenario analysis:
1) All business beans should be enhanced, but there are no rules for bean names.
2) Enhance the business functions of bean objects according to business modules (businesses under different packages).

  • Execution expression (understand)

The execution expression is applied to the method level to achieve fine-grained pointcut expression definition. Case analysis:
Syntax: execution (return value type, package name, class name, method name (parameter list)).

  • Execution (void AOP. Service. Userserviceimpl. Adduser()) matches the addUser method.
  • The execution (void AOP. Service. Personserviceimpl. AddUser (string)) method parameter must be the addUser method of string.
  • execution( aop.service... * (..) universal configuration.

Slice priority setting

The priority of the cutting plane needs the help of@OrderThe smaller the number, the higher the priority, and the lower the default priority.

Note: when multiple facets act on the same target object method, these facets will be constructed into a facet chain, similar to filter chain and interceptor chain. Its execution analysis is shown in the figure:
Spring framework learning

Declarative transaction

Transaction: transaction is a business and an inseparable logical work unit. Based on transaction, the correctness of business can be better guaranteed.

  • Either all succeed or all fail
  • Ensure integrity and consistency
  • Transaction is very important in project development, involving data consistency

Transaction acid principle

  • Atomicity: multiple operations in a transaction either succeed or fail.
  • Consistency: for example, when saving money, the total amount of money before and after saving should be the same.
  • Isolation: transactions and transactions should be isolated from each other.
  • Durability: once a transaction is committed, the data should be persisted.

@Transactional annotation configuration transaction

  1. Enable declarative transaction management. Add @ enabletransactionmanagement on the project startup class, or not in the new version (for example, the new spring boot project).
  2. Add the @ transactional annotation to the appropriate business class or method and set the appropriate attribute information.
 @Transactional(timeout = 30,
               readOnly = false,
               isolation = Isolation.READ_COMMITTED,
               rollbackFor = Throwable.class,
               propagation = Propagation.REQUIRED)
  @Service
  public class implements SysUserService {
        @Transactional(readOnly = true)
        @Override
        public PageObject<SysUserDeptVo> findPageObjects(
                        String username, Integer pageCurrent) {
      …
       }
}
  • When the @ transactional annotation is applied to a class, it means that all methods in the class start transaction management, and it is generally used for the definition of transaction commonness.
  • When @ transactional describes a method, it means that the method needs transaction management. If there are @ transactional annotations on both classes and methods, the transaction characteristics on the method have higher priority.
@Application description of common transactional attributes:
  • Timeout: the timeout of the transaction. The default value is – 1, indicating that no timeout is displayed. If a specific time is configured, if the time limit is exceeded but the transaction has not completed, the transaction will be rolled back automatically. This time is recorded after the transaction is started and before the SQL statement is executed.
  • Read only: Specifies whether the transaction is read-only. The default value is false; To ignore methods that do not require transactions, such as reading data, you can set read only to true. The value of read only for adding, modifying and deleting businesses should be false.
  • Rollback for: used to specify exception types that can trigger transaction rollback. If multiple exception types need to be specified, each type can be separated by commas.
  • no-rollback- for:          Throw the exception type specified by no rollback for without rolling back the transaction.
  • Isolation: the isolation level of the transaction. The default value is default. When multiple transactions are executed concurrently, dirty reads, non repeatable reads, phantom reads and other phenomena may occur. However, if you do not want these phenomena, you can consider modifying the isolation level of the transaction (but the higher the isolation level, the smaller the concurrency and the worse the performance)

XML configuration transaction

<! -- Configure declarative transactions -- >
<property name="dataSource" ref="dataSource"/>
/bean>
<! -- Realize transaction weaving in combination with AOP -- >
<! -- Configure re service notification -- >
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<!-- Which methods are configured with transactions -- >
<!-- Propagation characteristics of transaction: 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"/>
<tx:method name="*"propagation="REQUIRED"/>
</tx:attributes>
</tx:advice>

<!-- Configure transaction entry -- >
<!--   Com. Cy. Mapper. *. * (..) indicates all methods in all classes under the mapper package -- >
<aop:config>
<aop:pointcut id="txPointCut" expression="execution(* com.cy.mapper.*.*(..))">
<aop:advisor advice-ref="txAdvice" pointcut-ref="txPointCut"/>
</aop:config>

Analysis of transaction control process in spring, as shown in the figure below:

Spring framework learning
Spring transaction management is based on interface proxy (JDK) or dynamic bytecode (cglib) technology, and then implements transaction enhancement through AOP. When we execute the target method with transaction features added, the system will call the datasourcetransactionmanager object through the proxy object of the target object, execute the dobegin method at the beginning of the transaction, and execute the docommit or dorollback method at the end of the transaction.

Transaction propagation in spring

The transaction propagation feature refers to the propagation mode of transactions when the transaction methods in “different service objects” call each other, as shown in the figure:
Spring framework learning

  • @Transactional(propagation=Propagation.REQUIRED) 。

If the current transaction does not participate in the propagation of the current transaction, the default is to create a new transaction_ Required, which is suitable for most situations. Suppose servivex#methodx() works in a transaction environment (that is, they are enhanced by spring transactions), and the following call chains exist in the program:
Service1#method1() – > service2#method2() – > service3#method3(), then the three methods of the three service classes work in the same transaction through the transaction propagation mechanism of spring. As shown in the figure:
Spring framework learning
Code examples are as follows:

@Transactional(propagation = Propagation.REQUIRED)
        @Override
        public List<Node> findZtreeMenuNodes() {
                return sysMenuDao.findZtreeMenuNodes();
        }

Note: when a business object calls the above method, this method always works in an existing transaction method or a transaction method created by the caller.

  • @Transactional(propagation=Propagation.REQUIRES_NEW)。

It must be a new transaction. If there is a current transaction, suspend the current transaction and start a new transaction, as shown in the figure:
Spring framework learning
Code examples are as follows:

        @Transactional(propagation = Propagation.REQUIRES_NEW)
        @Override
        public void saveObject(SysLog entity) {
          sysLogDao.insertObject(entity);
        }

Note: when a business object calls the above business method, this method will always run in a new transaction.

Summary of transaction management in spring

Spring declarative transaction is the core and most commonly used function of spring. Because spring transparently implements the function of declarative transactions through the functions of IOC and AOP, ordinary developers basically do not need to understand the internal details of spring declarative transactions, but only need to know how to configure them. However, for medium and high-end developers, they also need to understand their internal mechanism.

Implementation of spring AOP asynchronous operation

In the process of developing the system, the performance of the system is usually considered. An important idea to improve the system performance is to change “serial” to “parallel”. Speaking of “parallelism” is naturally inseparable from “asynchrony”. Today, let’s talk about how to use spring’s @ async asynchronous annotation.

Asynchronous implementation of spring business

  1. Start asynchronous configuration

In the annotation based configuration, the @ enableasync annotation is used to declare asynchronous startup. In the spring boot project, the @ enableasync annotation is applied to the startup class. The code example is as follows:

@Enableasync // the thread pool is created when the spring container starts
   @SpringBootApplication
   public class Application {
        public static void main(String[] args) {
                SpringApplication.run(Application.class, args);
        }
}
  1. On the business methods that need to be executed asynchronously, use the @ async method to declare asynchronously

When we need to configure the connection pool provided by the spring framework, we can refer to the following code:

spring:
  task:
    execution:
      pool:
        Queue capacity: 128# blocking queue capacity
        Core size: 5# number of core threads
        Max size: 128# maximum number of threads
        Keep alive: 60000 # thread idle time
      thread-name-prefix: db-service-task-