编程知识 cdmana.com

Introduction to spring AOP

1.1 AOP summary

1.1.1 AOP What is it? ?

AOP It's a design idea , It's aspect oriented programming in the field of software design , He's object-oriented programming OOP A supplement and perfection of . It is in the way of precompiling and runtime dynamic proxy , A technique to add additional functions to a program dynamically and uniformly without modifying the source code .

1.1.2 AOP Application scenario analysis ?

In actual projects, the system is usually divided into two parts , Part of it is the core business , Part of it is non core business . In the programming implementation, we should first complete the implementation of the core business , For non core business, we usually cut into the system in a specific way , This is usually done with the help of AOP Realization .
AOP It's based on OCP( Opening and closing principle ), On the basis of not changing the core business code of the original system, some extended functions can be added dynamically and the object execution can be controlled . for example AOP Applied to project log processing , Transaction processing , Authority handling , Cache processing and so on .

1.1.3 AOP Application principle analysis

1) If the target is ( Proxied object ) Implementation interface , The bottom layer can use JDK The dynamic proxy mechanism creates a proxy object for the target object ( The target class and the proxy class implement a common interface ).
2) If the target is ( Proxied object ) No interface implemented , The bottom layer can use CGLIB The proxy mechanism creates a proxy object for the target object ( The proxy class created by default inherits the target object type ).
AOP Use... By default CGLIB agent , Add to use JDK Dynamic proxy can be found in the configuration file (application.properties) The configuration in is as follows :
spring.aop.proxy-target-class=false

1.2AOP Analysis of related terms

section (asprct): Cross section object , Generally, it is a concrete class object ( Can use @Acpect Statement ).
notice (Advice): An action performed at a particular connection point in a cross section ( Extend the functionality ), for example around,before,after etc. .
Connection point (joinpoint): A specific point in program execution generally refers to the method intercepted .
The breakthrough point (pointcut): For multiple connection points (Joinpoint) A definition , Generally, it can be understood as a set of multiple connection points .

2.Spring AOP Fast practice

2.1 Business description

Based on the core business of the project , Simple add log operation , With the help of SLF4J journal API Output the execution time of the target method .( Premise , Cannot modify the code of the target method - follow OCP principle )

2.2 Project creation and configuration

establish maven Project or add to an existing project AOP Start dependency :
<dependency>

       <groupId>org.springframework.boot</groupId>

       <artifactId>spring-boot-starter-aop</artifactId>

</dependency>

explain : Based on this dependence spring Can integrate AspectJ Frame quick lock complete AOP Basic operation ,AspectJ It's a faceted framework , It defines the AOP Some of the syntax , There is a dedicated self generator to generate compliance java canonical class file .

2.3 Extended business analysis and Implementation

2.3.1 Create log facet class objects

Use this log facet class as a core business enhancement ( A cross section object ) class , It is used to output the service execution time .
package com.cy.pj.common.aspect;

@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();// Finally, the target method 

                   log.info("after:{}"+System.currentTimeMillis());

                   return result;

                 }catch(Throwable e) {

                   log.error("after:{}",e.getMessage());

                   throw e;

                 }

         }
explain :
@Aspect Annotations are used to identify or describe AOP The type of midplane , The object based on facet type is used to extend the function of the target object or control the execution of the target object .
@Pointcut Annotations are used to describe methods in facets , And define the entry point in the facet ,( Description Based on a specific expression ).
@Around Annotations are used to describe methods in aspects , Such an approach would be considered a circular notification ( An action to be performed before and after the core business method is executed ),@Around Notes inside value Property is a pointcut expression or a reference to a pointcut expression ( This quote is @Pointcut The method name of the method described by the annotation ).
ProceedingJoinPoint Class as a join point type , This type of object is used to encapsulate some information about the target method to be executed . It can only be used for @Around Annotation describes the method parameters .

2.3.1 Business aspect test implementation

Start project testing or unit testing :
@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());

         }

}

2.4 Analysis on the enhancement of extended service weaving

2.4.1 be based on JDK Proxy mode to achieve

If the target object has an implementation interface , It can be based on JDK Create a proxy object for the target object , Then extend the function of the target object .

2.4.2 be based on CGLIB Proxy mode to achieve

Adding a target object does not implement an interface ( Of course, it's OK to implement the interface ), Can be based on CGLIB Proxy mode weaves function extension for target object .
explain : The target object implements the interface and can also be based on CGLIB Create an object for the target object .

3.Spring AOP enhance

3.1 Aspect notification application enhancement

3.1.1 Notification type

Based on Spring AOP In the process of programming , be based on AspectJ Framework standard ,spring Five types of notifications are defined in ( Notification description is an extended business ), They are :
@Before
@AfterReturning
@AfterThrowing
@After
@Around Focus on mastering ( The highest priority )
explain : What notifications are used in facet classes , It's up to the business to decide , Is not to say that , All notices should be written in the section .

3.1.2 Notification execution order

image

explain : In a real project, all notifications may not be defined in facets , The specific definition of those notifications should be implemented in combination with the business .

3.1.3 Analysis of notification practice process

@Component

@Aspect

public class SysTimeAspect {

        @Pointcut("bean(sysUserServiceImpl)")

        public void doTime(){}


        @Before("doTime()")

        public void doBefore(JoinPoint jp){

                System.out.println("time doBefore()");

        }

        @After("doTime()")

        public void doAfter(){

                System.out.println("time doAfter()");

        }

        /** At the normal end of the core business *  explain : If there is after, Execute first after, Re execution returning*/

        @AfterReturning("doTime()")

        public void doAfterReturning(){

                System.out.println("time doAfterReturning");

        }

        /** Execute instructions when core business is abnormal : If there is after, Execute first after, Re execution Throwing*/

        @AfterThrowing("doTime()")

        public void doAfterThrowing(){

                System.out.println("time doAfterThrowing");

        }

        @Around("doTime()")

        public Object doAround(ProceedingJoinPoint jp)

                        throws Throwable{

                System.out.println("doAround.before");

         try{

                 Object obj=jp.proceed();

           System.out.println("doAround.after");

          return obj;

                 }catch(Throwable e){

          System.out.println(e.getMessage());

          throw e;

         }

                

        }

}
explain : about @AfterThrowing Notification is only executed when there is an exception , Therefore, as some exception monitoring, code implementation can be carried out in this method .

3.2 Pointcut expression enhancement

3.2.1bean expression ( a key )

bean Expressions are generally applied at the class level , Implement coarse-grained pointcut definitions , case analysis :
bean("userServiceImpl") To specify a userServiceImpl All the methods in .
bean("*ServiceImpl") Specifies that all suffixes are ServiceImpl All methods in the class of .
explain :bean The object inside an expression is defined by spring One of container management bean object , The name inside the expression should be spring One of the containers bean Of name.

3.2.2within expression ( understand )

within Expressions are applied at the class level , Implement coarse-grained pointcut expression definitions , 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 .
within("aop.service..*") Specifies all methods of classes in the current directory and subdirectories .

3.2.3execution expression ( understand )

execution Expressions are applied at the method level , Implement fine-grained pointcut expression definitions , case analysis :
grammar :execution( return type Package name . Class name . Method name ( parameter list )).
execution(void aop.service.UserServiceImpl.addUser()) matching addUser Method .
execution(void aop.service.PersonServiceImpl.addUser(String)) Method parameter must be String Of addUser Method
execution( aop.service...*(..)) Universal configuration .

3.2.4@annotation expression ( a key )

@annontation(anno.RequiredLog) Match the method described by this annotation .
@annontation(anno.RequiredCache) Match the method described by this annotation .
among :RequiredLog Customize annotations for us , When we use @RequiredLog When annotations modify business level methods , The bottom layer of the system will perform daily extension operation when executing this method .
: To define a Cache Relevant section , Use annotation expressions to define pointcuts , And use this annotation for the need to use cache To describe the business method of , The code analysis is as follows :
First step : Definition notes RequiredCache
package com.cy.pj.common.annotation;

/**

 *  Custom annotation , A special class , All annotations inherit by default Annotation Interface 

 */

@Retention(RetentionPolicy.RUNTIME)

@Target(ElementType.METHOD)

public @interface RequiredCache {

   //...

}
The second step : Definition SysCacheAspect Tangent object
package com.cy.pj.common.aspect;

@Aspect

@Component

public class SysCacheAspect {

            @Pointcut("@annotation(com.cy.pj.common.annotation.RequiredCache)")

          public void doCache() {}


          @Around("doCache()")

          public Object around(ProceedingJoinPoint jp)

    throws Throwable{

                  System.out.println("Get data from cache");

                  Object obj=jp.proceed();

                  System.out.println("Put data to cache");

                  return obj;

          }

   

}
The third step : Use @RequiredCache Annotations describe the query methods in specific business target objects .
 @RequiredCache

        @Override

        public List<Map<String, Object>> findObjects() {

                ….

                return list;

        }

3.3 Facet priority setting implementation

The priority of facets needs the help of @Order Comments describe , The smaller the number, the higher the priority , The default priority is low . for example :
Define log facets and specify priorities
@Order(1)

@Aspect

@Component

public class SysLogAspect {

 …

}
Define cache facets and specify priorities
@Order(2)

@Aspect

@Component

public class SysCacheAspect {

        …

}
explain : When multiple facets act on the same target object method , These facets form a chain of facets , It's like a filter chain 、 The interceptor chain .

3.4 Summary of key objects and terms

Spring be based on AspectJ Framework implementations AOP Overview of key objects of design , Pictured -10 Shown :

image

版权声明
本文为[BolunWu]所创,转载请带上原文链接,感谢

Scroll to Top