Spring之AOP理解

10、代理模式

spring AOP的底层【springAOP和springMVC】

代理模式的分类:

  • 静态代理
  • 动态代理

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-QMovlTta-1647688851311)(1、Spring.assets/image-20220317105927989-16474859729741.png)]

10.1 静态代理

角色分析:

  • 抽象角色:一般会使用接口或者抽象类来解决
  • 真实角色:被代理的角色
  • 代理角色:代理真实角色,代理真实角色后,一般会做一些附属操作
  • 客户:访问代理对象的人

代码步骤:

  1. 接口
//租房
public interface Rent {
    public void rent();
}

2.真实角色

public class Host implements Rent {
    @Override
    public void rent() {
        System.out.println("房东要出租房子");
    }
}

3.代理角色

public class proxy implements Rent {
    private Host host;

    public proxy() {
    }

    public proxy(Host host) {
        this.host = host;
    }

    @Override
    public void rent() {
        host.rent();
    }

    public void seeHouse() {
        System.out.println("中介带你看房");
    }
}

4.客户端访问代理角色

public class Client {
    public static void main(String[] args) {
        Host host = new Host();
        proxy proxy = new proxy(host);
        proxy.seeHouse();
        proxy.rent();
    }
}

代理模式的好处:

  • 可以使真实角色的操作更加纯粹
  • 公共业务就交给了代理角色,实现了业务分工
  • 公共业务发生扩展的时候,方便集中管理

缺点:

一个真实角色就会产生一个代理角色,代码量翻倍

10.2 动态代理

  • 动态代理和静态代理角色一样
  • 动态代理的类是动态生成的不是我们直接写好的
  • 动态代理分为两大类:基于接口的动态代理,基于类的动态代理
    • 基于接口—jdk动态代理
    • 基于类:cgllb
    • 基于java字节码

需要了解两个类:Proxy:代理、InvocationHandler:调用处理

动态代理的好处:

  • 可以使真实角色的操作更加纯粹,不用去关注一些公共的业务
  • 公共业务就交给代理角色,实现了业务的分工
  • 公共业务发生扩展的时候,方便集中管理
  • 一个动态类代理的是一个接口,一般就是对应的一类业务
  • 一个动态代理类可以代理多个类,只要是实现了接口就行

11、AOP

11.1 什么是AOP

在软件业,AOP为Aspect Oriented Programming的缩写,意为:面向切面编程,通过预编译方式和运行期间动态代理实现程序功能的统一维护的一种技术。AOP是OOP的延续,是软件开发中的一个热点,也是Spring框架中的一个重要内容,是函数式编程的一种衍生范型。利用AOP可以对业务逻辑的各个部分进行隔离,从而使得业务逻辑各部分之间的耦合度降低,提高程序的可重用性,同时提高了开发的效率。

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-5ztIOBvi-1647688851312)(1、Spring.assets/image-20220319170045147-16476804499881.png)]

11.2 AOP在spring中的作用

提供声明式事务,允许用户自定义切面

  • 横切关注点:跨越应用程序多个模块的方法或者功能。既是,与我们业务逻辑无关的,但是我们需要关注的部分,就是横切关注点,如日志,安全,缓存,事务等等……
  • 贴面:横切关注点被模块化的特殊对象,是一个类
  • 通知:切面必须要完成的工作,是类中的一个方法
  • 目标:被通知的对象
  • 代理:想目标对象通知之后创建的对象
  • 切入点:切面通知执行“地点”的定义
  • 连接点:与切入点匹配的执行点

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-tuLo5pPE-1647688851313)(1、Spring.assets/image-20220319171034143-16476810414132.png)]

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-KiQiIBfE-1647688851313)(1、Spring.assets/image-20220319171147160-16476811094393.png)]

11.3 使用spring实现AOP

【重点】使用AOP之前,需要导入一个依赖包

<dependencies>
    <dependency>
        <groupId>org.aspectj</groupId>
     	<artifactId>aspectjweaver</artifactId>
        <version>1.9.8</version>
    </dependency>
</dependencies>

方式一:使用spring的API接口

<?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: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/aop
       https://www.springframework.org/schema/aop/spring-aop.xsd">

    <bean id="userService" class="com.xlb.service.UserServiceImpl"/>
    <bean id="log" class="com.xlb.log.Log"/>
    <bean id="afterLog" class="com.xlb.log.AfterLog"/>

    <!--方式一:使用原生Spring API接口-->
    <!--配置AOP:需要导入AOP的约束-->
    <aop:config>
        <!--切入点:expression:表达式,execution(要执行的位置)-->
        <aop:pointcut id="pointcut" expression="execution(* com.xlb.service.UserServiceImpl.*(..))"/>

        <!--执行环绕增加-->
        <aop:advisor advice-ref="log" pointcut-ref="pointcut"/>
        <aop:advisor advice-ref="afterLog" pointcut-ref="pointcut"/>
    </aop:config>

</beans>
package com.xlb.service;

public interface UserService {
    public void add();
    public void delete();
    public void update();
    public void query();
}
package com.xlb.service;

public class UserServiceImpl implements UserService {
    @Override
    public void add() {
        System.out.println("增加了一个用户");
    }

    @Override
    public void delete() {
        System.out.println("删除了一个用户");
    }

    @Override
    public void update() {
        System.out.println("修改了一个用户");
    }

    @Override
    public void query() {
        System.out.println("查找了一个用户");
    }
}
package com.xlb.log;

import org.springframework.aop.MethodBeforeAdvice;

import java.lang.reflect.Method;

//method:要执行的目标对象的方法
//objects:参数
//target:目标对象
public class Log implements MethodBeforeAdvice {
    @Override
    public void before(Method method, Object[] args, Object target) throws Throwable {
        System.out.println(target.getClass().getName()+"的"+method.getName()+"被执行了");
    }
}
package com.xlb.log;

import org.springframework.aop.AfterReturningAdvice;

import java.lang.reflect.Method;

public class AfterLog implements AfterReturningAdvice {
    @Override
//    returnValue:返回值
    public void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable {
        System.out.println("执行了" + method.getName() + ",返回的结果为" + returnValue);
    }
}
import com.xlb.service.UserService;
import com.xlb.service.UserServiceImpl;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MyTest {
    public static void main(String[] args) {
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
//        动态代理代理的是接口
        UserService userService = (UserService) context.getBean("userService");
        userService.add();
    }
}

方式二:使用自定义类实现AOP

<!--    方式二:自定义类-->
<bean id="diy" class="com.xlb.diy.DiyPrintCut"/>
<aop:config>
    <!--        自定义切面,ref要引用的类-->
    <aop:aspect ref="diy">
        <aop:pointcut id="point" expression="execution(* com.xlb.service.UserServiceImpl.*(..))"/>
        <aop:before method="before" pointcut-ref="point"/>
        <aop:after method="after" pointcut-ref="point"/>
    </aop:aspect>
</aop:config>
package com.xlb.diy;

public class DiyPrintCut {
    public void before(){
        System.out.println("======方法执行前=======");
    }
    public void after(){
        System.out.println("======方法执行后=======");
    }
}

方式三:使用注解实现

package com.xlb.diy;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.*;

@Aspect//标注这个类是一个切面
public class AnnotationPointCut {

    @Before("execution(* com.xlb.service.UserServiceImpl.*(..))")
    public void before() {
        System.out.println("======方法执行前======");
    }

    @After("execution(* com.xlb.service.UserServiceImpl.*(..))")
    public void after() {
        System.out.println("======方法执行后======");
    }

    //    在环绕增强中可以给定一个参数代表我们要获取切入的点
    @Around("execution(* com.xlb.service.UserServiceImpl.*(..))")
    public void around(ProceedingJoinPoint jp) {
        System.out.println("环绕前");

        Signature signature = jp.getSignature();
        System.out.println(signature);

        try {
            Object proceed = jp.proceed();
        } catch (Throwable e) {
            e.printStackTrace();
        }

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小笼包吃汤包

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值