Spring Boot2 (6): Use Spring Boot integrate AOP Aspect Oriented Programming

I. Introduction

As we all know, spring is the core of the two functions and aop ioc, namely Aspect Oriented and Inversion of Control. This article will talk about how to use AOP SpringBoot implement the aspect of process-oriented principles.

Second, what is aop

aop full name Aspect Oriented Programming, aspect-oriented, the main object of the AOP is achieved for the extraction of business process section, it is facing a specific step or stage process to obtain a coupling between a logic low during portions of isolation. Its completion and design patterns similar task, is to provide another angle to think about the structure of the program to compensate for the lack of object-oriented programming.

  Popular speak is to provide a mechanism for providing a service to the injection section to achieve, in this way, it will be defined in well service operation section to the service binding through an entry point to achieve some special logic to this binding business.

  For chestnuts, projects demand record operating logs, or process changes are recording change history, is nothing more than plug operating table, save a very simple operation, are some of the logging or other ancillary code. Over and over again and rewrite the call. Not only a waste of time, turn the project becomes more redundancy, it is not worth the candle.

  Aspect Oriented aop so we need to play.

Three, aop relative term.

To understand SpringBoot aop achieve integration, we must first understand the aop section for some of the implementation of the name, or is foggy.

  • Section (Aspect) : a modular point of concern. @Aspect in the form of notes on the top of the class, declare a section.

  • Connection point (Joinpoint) : during program execution in a particular point, such as when a method or the handling of an exception may be the point of attachment.

  • Notice (the Advice) : notification enhancement, called the notice needs to be done, it is that you need to write business logic in such matters, logs, etc. to define good and where it is needed to go with.

    Including 5 Notes: Before, After, AfterReturning, AfterThrowing, Around.

    @Before: executed before the cut-point method.

    @After: The method is performed after the point of tangency

    @AfterReturning: After cut-point return method of performing

    @AfterThrowing: cut-point method throwing error execution

    @Around: belong to surround enhancement can be controlled cut-off point before the execution, after execution, with this annotation, the program throw an exception, this will affect @AfterThrowing comment

  • Cut-off point (Pointcut) : in fact screened connection point , the connection point of the match assertion, all methods of a class are connection points, but not all needed, it will filter out some of the cut-off point as a connection point . If the notification section defines the action or execution timing, then cut-off point defines the place of execution. How pointcut expressions and the connection point matching is central to AOP: Spring uses the AspectJ pointcut default syntax.

  • Introducing (Introduction) : in without changing an existing class code, add properties and methods for the class, without modifying the conventional can type in the premise that they would have a new behavior and state. In fact, the section: use the target class (that is, the new notification method attribute defined) to go.

  • Audience (the Target Object) : Object to be notified to one or more facets. Also referred to as notification (adviced) objects. Since Spring AOP is achieved by running a proxy, this object is always to be a proxy (proxied) objects.

  • AOP proxy (Proxy AOP) : Object created by the AOP framework to implement the aspect contracts (advise method executions and so on). In Spring, AOP proxy will be a JDK dynamic proxy or proxy CGLIB.

  • Weaving (Weaving) : the aspects with other application types or objects, and create an object to be notified. These may be at compile time (e.g., using the AspectJ compiler), load time, and runtime. Spring and other pure Java AOP frameworks, performs weaving at runtime.

One important nouns: section (Aspect) , the entry point (Pointcut)

Fourth, code implementation

Business logic to process logs, for example, the new log processing section for processing.

1. Add rely maven

<!--引入AOP依赖-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-aop</artifactId>
    <version>2.1.6.RELEASE</version>
</dependency>

2. Add the system log notes

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface SysLog {
    String value() default "";
}

3. Add the system log entity class

@Data
public class SysLogEntity {
    private String className;
    private String methodName;
    private String params;
    private Long exeuTime;
    private String remark;
    private String createDate;
}

4. New Service logic layer

@Slf4j
@Service
public class SysLogService {
    public boolean save(SysLogEntity sysLogEntity){
        // 这里就不做具体实现了
        log.info(sysLogEntity.getParams());
        return true;
    }
}

Here with the @ Slf4j log notes

Equivalent private final Logger logger = LoggerFactory.getLogger (XXX.class);

Simplifies the code, how to simplify how ~

Here it is to study aop of how to achieve, not specifically write code Service layer of.

5.Controller layer

@RestController
@RequestMapping("/aop")
public class AopController {
    @SysLog("测试")
    @GetMapping("/test")
    public String test(@RequestParam("name") String name, @RequestParam("age") int age){
        return name + ", " + age;
    }
}

6. processing section

To slightly to slightly, slightly key processing, the following code Keguan

First, in the top of the class declaration

@Aspect //使用@Aspect
@Component

Service call Service

@Autowired
private SysLogService sysLogService;

Add cut-off point expression @Pointcut

/**
 * 这里我们使用注解的形式
 * 当然,我们也可以通过切点表达式直接指定需要拦截的package,需要拦截的class 以及 method
 * 切点表达式:   execution(...)
 */
@Pointcut("@annotation(com.niaobulashi.anno.SysLog)")
public void logPointCut() {}

Add around advice @Around

@Around("logPointCut()")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        long beginTime = System.currentTimeMillis();
        Object result = point.proceed();
        long time = System.currentTimeMillis() - beginTime;
        try {
            //实现保存日志逻辑
            saveLog(point, time);
        } catch (Exception e) {
            
        }
        return result;
    }

Save the log to achieve a logical saveLog

private void saveLog(ProceedingJoinPoint joinPoint, long time) {

    // 获取方法的关键信息,类,包
    MethodSignature signature = (MethodSignature) joinPoint.getSignature();
    Method method = signature.getMethod();
    SysLogEntity sysLogEntity = new SysLogEntity();
    sysLogEntity.setExeuTime(time);
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
    sysLogEntity.setCreateDate(dateFormat.format(new Date()));
    SysLog sysLog = method.getAnnotation(SysLog.class);
    if(sysLog != null) {
        //注解上的描述
        sysLogEntity.setRemark(sysLog.value());
    }
    //请求的 类名、方法名
    String className = joinPoint.getTarget().getClass().getName();
    String methodName = signature.getName();
    sysLogEntity.setClassName(className);
    sysLogEntity.setMethodName(methodName);
    //请求的参数
    Object[] args = joinPoint.getArgs();
    try {
        List<String> list = new ArrayList<String>();
        for (Object o : args) {
            list.add(o.toString());
        }
        sysLogEntity.setParams(list.toString());
    } catch (Exception e){

    }
    sysLogService.save(sysLogEntity);
}

MethodSignature main achievement is the return value class, method name and parameters in the form of

Five test

By sending a get request: 127.0.0.1: 8081 / aop / test name = Tom & age = 18?

At the same time run the project in debug mode, check the parameters RBI

You can see the parameters MethodSignature

And the various parameters sysLogEntity assignment.

VI Summary

1, crosscutting concerns
intercepts which methods, how to deal with the interception, these concerns called crosscutting concerns

2, section (aspect) -> (+ notification tangent point)
is the abstract features of the object, section of the abstract crosscutting concerns.
Notice + cut-off point
means that all the places to be applied to enhance the (advice) code. (Including location information method)

3、连接点(joinpoint)->(被拦截的方法)
被拦截到的点,因为Spring只支持方法类型的连接点,所以在Spring中连接点指的就是被拦截的方法,实际上连接点还可以是字段或者构造器

4、切入点(pointcut)->(描述拦截那些方法的部分)
对连接点进行拦截的定义

5、通知(advice)->(拦截后执行自己业务逻辑的那些部分)
所谓通知指的就是指拦截到连接点之后要执行的代码,通知分为前置、后置、异常、最终、环绕通知五类
这玩意也叫 增强

在逻辑层次上包括了我们抽取的公共逻辑和方位信息。因为Spring只能方法级别的应用AOP,也就是我们常见的before,after,after-returning,after-throwing,around五种,意思就是在方法调用前后,异常时候执行我这段公共逻辑呗。

推荐阅读

【spring-boot】spring aop 面向切面编程初接触

Spring Boot中使用AOP统一处理Web请求日志

Guess you like

Origin www.cnblogs.com/niaobulashi/p/springboot-aop.html