Spring5框架(AOP)

1、什么是 AOP

(1)面向切面编程(方面),利用 AOP 可以对业务逻辑的各个部分进行隔离,从而使得业务逻辑各部分之间的耦合度降低,提高程序的可重用性,同时提高了开发的效率。

(2)通俗描述:不通过修改源代码方式,在主干功能里面添加新功能

(3)使用登录例子说明 AOP

在这里插入图片描述

AOP(底层原理)

1、AOP 底层使用动态代理
(1)有两种情况动态代理

第一种 有接口情况,使用 JDK 动态代理

  • 创建接口实现类代理对象,增强类的方法
    在这里插入图片描述

第二种 没有接口情况,使用 CGLIB 动态代理

  • 创建子类的代理对象,增强类的方法在这里插入图片描述

AOP(JDK 动态代理)

1、使用 JDK 动态代理,使用 Proxy 类里面的方法创建代理对象
在这里插入图片描述
(1)调用 newProxyInstance 方法
在这里插入图片描述
方法有三个参数:
第一参数,类加载器
第二参数,增强方法所在的类,这个类实现的接口,支持多个接口
第三参数,实现这个接口 InvocationHandler,创建代理对象,写增强的部分

2、编写 JDK 动态代理代码
(1)创建接口,定义方法

public interface UserDao {
    public int add(int a, int b);
    public String update(String id);
}

(2)创建接口实现类,实现方法

/**
 * @author acoffee
 * @create 2021-03-16 20:43
 */
public class UserDaoImpl implements UserDao {

    @Override
    public int add(int a, int b) {
        System.out.println("add方法执行了....");
        return a+b;
    }

    @Override
    public String update(String id) {
        System.out.println("update方法执行了");
        return id;
    }
}

(3)使用 Proxy 类创建接口代理对象

/**
 * @author acoffee
 * @create 2021-03-16 20:45
 */
public class JDKProxy {
    public static void main(String[] args) {
        //创建接口实现类代理对象
        Class[] interfaces = {UserDao.class};
//        Proxy.newProxyInstance(JDKProxy.class.getClassLoader(), interfaces, new InvocationHandler() {
//            @Override
//            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
//                return null;
//            }
//        });
        UserDaoImpl userDao = new UserDaoImpl();
        UserDao dao = (UserDao) Proxy.newProxyInstance(JDKProxy.class.getClassLoader(), interfaces, new UserDaoProxy(userDao));
        int add = dao.add(1, 2);
        System.out.println("result:"+add);
    }
}


//创建代理对象代码
class UserDaoProxy implements InvocationHandler{

    //1.把创建的是谁的代理对象,把谁传递过来
    //有参数的构造进行传递
    private Object obj;
    public UserDaoProxy(Object obj){
        this.obj = obj;
    }

    //增强的逻辑
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        //方法之前
        System.out.println("在方法之前执行......"+method.getName()+":传递的参数..."+ Arrays.toString(args));

        //被增强的方法执行
        Object res = method.invoke(obj, args);

        //方法之后
        System.out.println("方法之后执行...."+obj);
        return res;
    }
}

执行结果:
在这里插入图片描述

AOP(术语)

1、连接点
类里面哪些方法可以被增强,这些方法称为连接点

2、切入点
实际被真正增强的方法,称为切入点

3、通知(增强)

(1)实际增强的逻辑部分称为通知(增强),比如登录功能我们加一个权限判断,而这个权限判断就是通知

(2)通知有多种类型

假如现在我们要增强add方法

  • 前置通知:add方法之前执行
  • 后置通知:add方法之后执行
  • 环绕通知:add方法的前面和后面都执行
  • 异常通知:当add方法出现异常执行
  • 最终通知:类似try-catch-finally中的finally方法,总会执行

4、切面
是动作
把通知应用到切入点的过程,假如为登陆方法加权限判断,加权限判断这个过程就是切面。

AOP 操作(准备工作)

1、Spring 框架一般都是基于 AspectJ 实现 AOP 操作
(1)AspectJ 不是 Spring 组成部分,独立 AOP 框架,一般把 AspectJ 和 Spirng 框架一起使用,进行 AOP 操作

2、基于 AspectJ 实现 AOP 操作
(1)基于 xml 配置文件实现
(2)基于注解方式实现(使用)

3、在项目工程里面引入 AOP 相关依赖
在这里插入图片描述
4、切入点表达式
(1)切入点表达式作用:知道对哪个类里面的哪个方法进行增强
(2)语法结构: execution([权限修饰符] [返回类型] [类全路径] [方法名称] ([参数列表]) )

举例 1:对 com.atguigu.dao.BookDao 类里面的 add 进行增强
execution(* com.atguigu.dao.BookDao.add(…))

*表示任意权限修饰符,public、private都可以
返回类型上述我们是省略了的
com.atguigu.dao.BookDao表示类全路径
add( )表示方法
(…)在add方法后面的括号中表示参数列表

举例 2:对 com.atguigu.dao.BookDao 类里面的所有的方法进行增强
execution( com.atguigu.dao.BookDao. * (…))

举例 3:对 com.atguigu.dao 包里面所有类,类里面所有方法进行增强
execution(* com.atguigu.dao.* .* (…))

AOP 操作(AspectJ 注解)

1、创建类,在类里面定义方法

/**
 * @author acoffee
 * @create 2021-03-17 19:05
 */

//被增强类
public class User {
    public void add(){
        System.out.println("add......");
    }
}

2、创建增强类(编写增强逻辑)
(1)在增强类里面,创建方法,让不同方法代表不同通知类型

//增强的类
public class UserProxy {

    // 前置通知
    public void before(){
        System.out.println("before......");
    }
}

3、进行通知的配置
(1)在 spring 配置文件中,开启注解扫描

<?xml version="1.0" encoding="UTF-8"?>
<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:aop="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 http://www.springframework.org/schema/context/spring-context.xsd
                           http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">


    <!--开启注解扫描-->
    <context:component-scan base-package="com.acoffee.spring5.aopanno"></context:component-scan>
</beans>

(2)使用注解创建 User 和 UserProxy 对象
在这里插入图片描述
在这里插入图片描述
(3)在增强类上面添加注解 @Aspect
在这里插入图片描述
(4)在 spring 配置文件中开启生成代理对象
在这里插入图片描述
4、配置不同类型的通知
(1)在增强类的里面,在作为通知方法上面添加通知类型注解,使用切入点表达式配置

前置通知:

//增强的类
@Component
@Aspect
public class UserProxy {

    // 前置通知
    @Before(value = "execution(* com.acoffee.spring5.aopanno.User.add(..))")
    public void before() {
        System.out.println("before......");
    }

    //后置通知(返回通知)
    @After(value = "execution(* com.acoffee.spring5.aopanno.User.add(..))")
    public void after() {
        System.out.println("after....");
    }

    //最终通知
    @AfterReturning(value = "execution(* com.acoffee.spring5.aopanno.User.add(..))")
    public void AfterReturning() {
        System.out.println("AfterReturning....");
    }

    //异常通知
    @AfterThrowing(value = "execution(* com.acoffee.spring5.aopanno.User.add(..))")
    public void AfterThrowing() {
        System.out.println("AfterThrowing....");
    }

    //环绕通知
    @Around(value = "execution(* com.acoffee.spring5.aopanno.User.add(..))")
    public void Around(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        System.out.println("环绕之前....");
        //被增强的方法
        proceedingJoinPoint.proceed();

        System.out.println("环绕之后....");
    }

}

测试类:

public class TestAop {
    @Test
    public void testAopAnno() {
        ApplicationContext context =
                new ClassPathXmlApplicationContext("bean1.xml");

        User user = context.getBean("user", User.class);
        user.add();
    }
}

执行结果:
在这里插入图片描述
我们根据以上结果可以发现,异常通知是没有执行的。如果我们在被增强类上上加异常,如下:

//被增强类
@Component
public class User {
    public void add() {
        int i = 10 / 0;//我们增加的异常
        System.out.println("add......");
    }
}

则执行结果会变为:
在这里插入图片描述
after 执行的原因是因为after为最终通知不管有没有异常最终都会执行。

5、相同的切入点抽取

    //相同切入点抽取
    @Pointcut(value = "execution(* com.acoffee.spring5.aopanno.User.add(..))")
    public void pointdemo(){
    
    }

    // 前置通知
    @Before(value = "pointdemo()")
    public void before() {
        System.out.println("before......");
    }

就相当于直接用 pointdemo() 这个方法代替了切入点

6、有多个增强类多同一个方法进行增强,设置增强类优先级
(1)在增强类上面添加注解 @Order(数字类型值),数字类型值越小优先级越高

UserProxy类:
在这里插入图片描述
PersonProxy类:
在这里插入图片描述
执行结果:
在这里插入图片描述
7、完全使用注解开发
(1)创建配置类,不需要创建 xml 配置文件

//完全注解开发
@Configuration
@ComponentScan(basePackages = {"com.acoffee"})
@EnableAspectJAutoProxy(proxyTargetClass = true)
public class ConfigAop {
}

AOP 操作(AspectJ 配置文件,实际情况下我们一般用的较少,一般使用注解的方式)

1、创建两个类,增强类和被增强类,创建方法

//被增强类
public class Book {

    public void buy(){
        System.out.println("buy......");
    }
}
//增强类
public class BookProxy {

    public void before(){
        System.out.println("before.....");
    }
}

2、在 spring 配置文件中创建两个类对象

    <!--创建两个类的对象-->
    <bean id="book" class="com.acoffee.spring5.aopxml.Book"></bean>
    <bean id="bookpProxy" class="com.acoffee.spring5.aopxml.BookProxy"></bean>

3、在 spring 配置文件中配置切入点

    <!--配置aop增强-->
    <aop:config>
        <!--切入点-->
        <aop:pointcut id="p" expression="execution(* com.acoffee.spring5.aopxml.Book.buy(..))"/>

        <!--配置切面-->
        <aop:aspect ref="bookpProxy">
            <!--增强作用在具体的方法上,这里意思就是把before方法作用在buy方法上面-->
            <aop:before method="before" pointcut-ref="p"/>
        </aop:aspect>
    </aop:config>

测试类:

    @Test
    public void testAopXml() {
        ApplicationContext context =
                new ClassPathXmlApplicationContext("bean2.xml");

        Book book = context.getBean("book", Book.class);
        book.buy();
    }

执行结果:
在这里插入图片描述

重点掌握aop的概念、底层原理(有接口和没有接口的情况)、几个术语、AspectJ 的两个方式(重点是注解的方式)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值