20210325笔记

1. Spring AOP.

AOP: 面向切面编程  在不影响核心代码的前提下,可以在任意位置添加非核心代码。

2. AOP的前身

3. 通过动态代理实现核心业务和非核心业务的一种抽取。

比较麻烦

4. 可以使用spring 的aop来完成代理

(1) 把相关spring的依赖加入

   <dependencies>
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-webmvcartifactId>
            <version>5.2.9.RELEASEversion>
        dependency>

        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-jdbcartifactId>
            <version>5.2.9.RELEASEversion>
        dependency>

        
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-aspectsartifactId>
            <version>5.2.9.RELEASEversion>
        dependency>
    dependencies>

(2)创建一个切面类

package com.ykq.aop.after;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Arrays;

/**
 * @Author 闫克起
 * @Date 2021/3/25 15:52
 * @Version 1.0
 *
 * 日志切面类
 */
@Component
@Aspect //表示该类为切面类   -----> 删除某一个记录 添加日志。  操作日志
public class LogAspect {


    @Before(value = "execution(* com.aop.after.*.*(..))")  //service
    public void before(JoinPoint joinPoint){
        String name = joinPoint.getSignature().getName();
        Object[] args = joinPoint.getArgs();
        System.out.println("AAA--->The "+name+" method begin with "+ Arrays.asList(args));
    }

    @After(value = "execution(* com.aop.after.*.*(..))")  //后置通知 finally
    public void after(JoinPoint joinPoint){
        System.out.println("该方法总会被执行");
    }
    @AfterReturning(value = "execution(* com.aop.after.*.*(..))",returning = "r")     //后置返回通知  他可以得到返回结果。
    public void afterReturning(JoinPoint joinPoint,int r){
        String name = joinPoint.getSignature().getName();
        System.out.println("BBB--->The "+name+" method ends: "+r);
    }

    //catch(Exception e)
    @AfterThrowing(value = "execution(* com.aop.after.*.*(..))",throwing = "e")   //异常通知 只有发生异常时才会被执行。
    public void afterThrowing(Exception e){
        System.out.println(e.getMessage());
    }
}

(3) 配置文件开启切面注解


<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop.xsd">

    
    <context:component-scan base-package="com.aop.after"/>

    
    <mvc:aspectj-autoproxy />
beans>

你可能感兴趣的:(20210325笔记)