Spring:(三)AOP

3.1 AOP简介

3.1.1 AOP的概念

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

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

使用登录例子说明 AOP:

image-20220724004313458

3.2.2 AOP底层原理

AOP 底层使用动态代理,有两种情况的动态代理

  1. 有接口情况,使用 JDK 动态代理,创建接口实现类代理对象,增强类的方法

    image-20220724004622025

  2. 没有接口情况,使用 CGLIB 动态代理,创建子类的代理对象,增强类的方法

    image-20220724004657451

3.2 JDK动态代理

3.2.1 newProxyInstance

JDK 动态代理使用 Proxy 类里面的newProxyInstance()方法创建代理对象。

  • newProxyInstance 方法

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-rVt19wEi-1658604183949)(../../AppData/Roaming/Typora/typora-user-images/image-20220724013911833.png)]

该方法有三个参数:

  • 第一参数,类加载器
  • 第二参数,增强方法所在的类实现的接口,支持多个接口
  • 第三参数,实现这个接口 InvocationHandler,创建代理对象,写增强的部分

3.2.2 JDK动态代理实例

  1. 创建接口,定义方法

    public interface Human {
        public void eat(String str);
    }
    
  2. 创建接口实现类,实现方法

    public class SuperMan implements Human{
        @Override
        public void eat(String str) {
            System.out.println("我喜欢吃" + str);
        }
    }
    
  3. 使用 Proxy 类创建接口代理对象

    class ProxyFactory{
        Object object;
    
        public ProxyFactory(Object object) {
            this.object = object;
        }
    
        public Object getInstance(){
            return Proxy.newProxyInstance(object.getClass().getClassLoader(), object.getClass().getInterfaces(), new InvocationHandler() {
                @Override
                public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                    // 在被代理对象的方法之上编写增强逻辑
                    System.out.println("吃东西前要洗手...");
                    Object returnValue = method.invoke(object, args);
                    System.out.println("吃完东西要刷牙...");
                    return returnValue;
                }
            });
        }
    }
    
  4. 代码测试

    public class TestProxy {
        @Test
        public void testProxy(){
            SuperMan superMan = new SuperMan();
            ProxyFactory proxyFactory = new ProxyFactory(superMan);
            Human human = (Human) proxyFactory.getInstance();
            human.eat("四川麻辣烫");
        }
    }
    

    [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-QCvWYaqq-1658604183949)(../../AppData/Roaming/Typora/typora-user-images/image-20220724015703260.png)]

3.3 AOP相关术语

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

  2. 切入点:实际上被增强的方法,被成为切入点

  3. 通知(增强):实际上增强的逻辑部分被称为通知(增强)

    通知有多重类型:

    • 前置通知
    • 后置通知
    • 环绕通知
    • 异常通知
    • 最终通知
  4. 切面:是一个动作,把通知应用到切入点的过程叫做切面

3.4 Spring的AOP操作流程

3.4.1 AspectJ

Spring 框架一般都是基于AspectJ 实现AOP操作,AspectJ不是 Spring组成部分,而是一个独立的AOP框架,一般把AspectJ和Spring框架一起使用,进行AOP操作。

3.4.2 切入点表达式

  • 切入点表达式作用:知道对哪个类里面的哪个方法进行增强
  • 语法结构: execution([权限修饰符] [返回类型] [类全路径] [方法名称]([参数列表])),其中中括号[]表示可选

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

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

3.4.3 基于AspectJ注解的AOP操作

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

    public class User {
        public void add(){
            System.out.println("我要执行加法");
        }
    }
    
  2. 创建增强类(编写增强逻辑)

    public class UserProxy {
        public void before() {//前置通知
            System.out.println("before......");
        }
    }
    
  3. 进行通知的配置

    <?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="atguigu"></context:component-scan>
        <!--开启AspectJ生成代理对象-->
        <aop:aspectj-autoproxy></aop:aspectj-autoproxy>
    </beans>
    
  4. 使用注解创建 User 和 UserProxy 对象

    @Component
    public class User {
        public void add(){
            System.out.println("我要执行加法");
        }
    }
    
    @Component
    public class UserProxy {
        public void before() {//前置通知
            System.out.println("before......");
        }
    }
    
  5. 在增强类上面添加注解 @Aspect

    @Component
    @Aspect
    public class UserProxy {
        public void before() {//前置通知
            System.out.println("before......");
        }
    }
    
  6. 配置不同类型的通知:在增强类的里面,在作为通知方法上面添加通知类型注解,使用切入点表达式配置

    @Component
    @Aspect
    public class UserProxy {
    
        @Before(value = "execution(* atguigu.pojo.User.add(..))")
        public void before() {//前置通知
            System.out.println("Before......");
        }
    
        @AfterReturning(value = "execution(* atguigu.pojo.User.add(..))")
        public void afterRunning() {
            System.out.println("After Running......");
        }
    
        @After(value = "execution(* atguigu.pojo.User.add(..))")
        public void after() {
            System.out.println("After.........");
        }
    
        @AfterThrowing(value = "execution(* atguigu.pojo.User.add(..))")
        public void afterThrowing() {
            System.out.println("AfterThrowing.........");
        }
    
        @Around(value = "execution(* atguigu.pojo.User.add(..))")
        public void around(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
            System.out.println("环绕之前.........");
            //被增强的方法执行
            proceedingJoinPoint.proceed();
            System.out.println("环绕之后.........");
        }
    
    }
    
  7. 相同的切入点抽取

    @Component
    @Aspect
    public class UserProxy {
        @Pointcut(value = "execution(* atguigu.pojo.User.add(..))")
        public void pointCut(){
    
        }
    
        @Before(value = "pointCut()")
        public void before() {//前置通知
            System.out.println("Before......");
        }
    
        @AfterReturning(value = "pointCut()")
        public void afterRunning() {
            System.out.println("After Running......");
        }
    
        @After(value = "pointCut()")
        public void after() {
            System.out.println("After.........");
        }
    
        @AfterThrowing(value = "pointCut()")
        public void afterThrowing() {
            System.out.println("AfterThrowing.........");
        }
    
        @Around(value = "pointCut()")
        public void around(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
            System.out.println("环绕之前.........");
            //被增强的方法执行
            proceedingJoinPoint.proceed();
            System.out.println("环绕之后.........");
        }
    }
    
  8. 有多个增强类多同一个方法进行增强,设置增强类优先级,在增强类上面添加注解 @Order(数字类型值),数字类型值越小优先级越高

    @Component
    @Aspect
    @Order(1)
    public class UserProxy {
    	...
    }
    

3.4.4 完全注解开发

创建配置类代替xml配置文件

@Configuration
@ComponentScan(value = "atguigu")
// proxyTargetClass = true:表示使用CGLIB实现代理类;默认为false:使用JDK实现代理类
@EnableAspectJAutoProxy(proxyTargetClass = true)
public class SpringConfig {
}

代码测试:

public class Test1 {
    @Test
    public void test(){
        ApplicationContext context = new AnnotationConfigApplicationContext(SpringConfig.class);
        User user = context.getBean("user", User.class);
        user.add();
    }
}

在这里插入图片描述

3.5 配置文件方式的AOP操作(已过时,了解即可)

  1. 创建对象

    <!--创建对象-->
    <bean id="user" class="atguigu.pojo.User"></bean>
    <bean id="userProxy" class="atguigu.pojo.UserProxy"></bean>
    
  2. 在 spring 配置文件中配置切入点

    <!--配置 aop 增强-->
    <aop:config>
        <!--切入点-->
        <aop:pointcut id="p" expression="execution(* atguigu.pojo.User.add(..))"/>
        <!--配置切面-->
        <aop:aspect ref="userProxy">
            <!--增强作用在具体的方法上-->
            <aop:before method="before" pointcut-ref="p"/>
        </aop:aspect>
    </aop:config>
    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值