【Spring三】动态代理, Spring-AOP

10.代理模式

代理模式的分类

  • 静态代理
  • 动态代理

image-20220331223032042

10.1,静态代理

角色分析

  • 抽象角色: 一般会使用接口或者抽象类来解决
  • 真实角色: 被代理的角色
  • 代理角色: 代理真实角色, 代理真实角色后, 我们一般会做一些附属操作
  • 客户: 访问代理对象的人
public class StaticProxy {
    public static void main(String[] args) {
        Host host = new Host();
        Proxy proxy = new Proxy(host);
        proxy.rent();
    }
}
//租房
interface Rent{
    void rent();
}
//房东
class Host implements Rent{
    @Override
    public void rent() {
        System.out.println("房东租房了");
    }
}
class Proxy implements Rent{
    private Host host;
    public Proxy(Host host) {
        this.host = host;
    }
    @Override
    public void rent() {
        doSomething();
        host.rent();
    }
    public void doSomething(){
        System.out.println("中介xxx");
        System.out.println("中介带你看房");
        System.out.println("中介带你签合同");
        System.out.println("收你中介费了");
    }
}

好处:

  • 可以控制对象的访问
  • 公共的地方抽离出来实现复用,代理对象可以附加一些方法

缺点:

  • 一个对象需要对应生成一个代理对象

10.2动态代理

  • 角色一样
  • 代理类是动态生成的
  • 动态代理分为两大类
    • 基于接口代理: JDK动态代理
    • 基于类的动态代理: cglib
    • java 字节码实现: javasist

需要了解两个类

  • Proxy (代理)
    • Proxy提供了创建动态代理类和实例的静态方法,它也是由这些方法创建的所有动态代理类的超类。
  • InvocationHandler (调用处理程序)
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class StaticProxy {
    public static void main(String[] args) {
        //真实角色
        Host host = new Host();
        //代理角色 : 生成
        ProxyInvocationHandler pih = new ProxyInvocationHandler();
        pih.setRent(host);
        //通过调用程序来处理我们要调用的接口对象
        Rent proxy = (Rent) pih.getProxy();//需转为接口, 不能转为实现类Host
        proxy.rent();
    }
}

//租房
interface Rent{
    void rent();
}

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

class ProxyInvocationHandler implements InvocationHandler {
    //被代理的接口
    private Object target;
    public void setRent(Object target){
        this.target = target;
    }
    //生成得到代理类
    public Object getProxy(){
        return Proxy.newProxyInstance(this.getClass().getClassLoader(),
                target.getClass().getInterfaces(),this);
    }
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println(method.getName());
        settHouse();
        //动态代理的本质, 使用反射机制实现
        Object result = method.invoke(target, args);//去调用了接口方法
        fare();
        return result;
    }
    //添加的方法
    public void settHouse(){
        System.out.println("中介带你看房子");
    }
    //添加的方法
    public void fare(){
        System.out.println("中介收你钱了");
    }
}

动态代理好处:

  • 可以控制对象的访问
  • 公共的地方抽离出来实现复用,代理对象可以附加一些方法
  • 一个动态代理类代理的是一个接口, 一般就是对应的一类业务
  • 一个动态代理类可以代理多个类, 只要实现了同一个接口

11.APO

不影响业务的情况下实现一些方法的增强

11.1.什么是AOP

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

image-20220401221714575

11.2.AOP在Spring中的作用

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

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

SpringAOP中,通过Advice定义横切逻辑,Spring中支持5种类型的Advice:

通知类型连接点实现接口
前置通知方法方法前org.springframework.aop.MethodBeforeAdvice
后置通知方法后org.springframework.aop.AfterReturningAdvice
环统通知方法前后org.aopalliance.intercept.MethodInterceptor
异常抛出通知方法抛出异常org.springframework.aop.ThrowsAdvice
引介通知类中增加新的方法属性org.springframework.aop.Introductionlnterceptor

即Aop在不改变原有代码的情况下,去增加新的功能。

方式一: 使用原生Spring API接口

service

public interface UserService {
    void insert();
    void update();
    void delete();
    void select();
}

public class UserServiceImpl implements UserService{
    @Override
    public void insert() {
        System.out.println("插入了一个用户");
    }

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

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

    @Override
    public void select() {
        System.out.println("查询了一个用户");
    }
}

log

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


public class AfterLog implements AfterReturningAdvice {
    /**
     *
     * @param returnValue   返回值
     * @param method
     * @param args
     * @param target
     * @throws Throwable
     */
    @Override
    public void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable {
        System.out.println("执行了"+method.getName()+",返回结果:" + returnValue);
    }
}

applicationContext.xml

<?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-2.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd ">
    <!--注册bean-->
    <bean id="userService" class="com.ccc.service.UserServiceImpl"/>
    <bean id="log" class="com.ccc.log.Log"/>
    <bean id="afterLog" class="com.ccc.log.AfterLog"/>
    <!--方式一, 使用原生Spring API接口-->
    <!--配置aop,需要aop的约束-->
    <aop:config>
        <!--切入点
                expression: 表达式
                execution:   要执行的位置(返回值  类名.方法名(参数)  )
                execution 要执行的位置! (*(修饰词) *(返回值) *(类名) *(方法名) *(参数))-->
        <aop:pointcut id="pointcut" expression="execution(* com.ccc.service.UserServiceImpl.*(..))"/>
        <!--执行环绕增加-->
        <aop:advisor advice-ref="log" pointcut-ref="pointcut"/>
        <aop:advisor advice-ref="afterLog" pointcut-ref="pointcut"/>
    </aop:config>
</beans>

test

public class Test {
    @org.junit.Test
    public  void test() {
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        //动态代理需要传入接口
        UserService userservice = context.getBean("userService", UserService.class);
        userservice.delete();
    }

}

方式二: 自定义类

自定义类

package com.ccc.diy;

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

xml

<?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-2.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd ">
    <!--注册bean-->
    <bean id="userService" class="com.ccc.service.UserServiceImpl"/>
    <bean id="log" class="com.ccc.log.Log"/>
    <bean id="afterLog" class="com.ccc.log.AfterLog"/>
    <!--方式一, 使用原生Spring API接口-->
    <!--方式二: 自定义类-->
    <bean id="diy" class="com.ccc.diy.DiyPointCut"/>
    <aop:config>
        <!--自定义切面, ref要引用的类-->
        <aop:aspect ref="diy">
            <!--切入点-->
            <aop:pointcut id="point" expression="execution(* com.ccc.service.UserServiceImpl.*(..))"/>
            <!--通知-->
            <aop:before method="before" pointcut-ref="point"/>
            <aop:after method="after" pointcut-ref="point"/>
        </aop:aspect>
    </aop:config>
</beans>

方式三: 注解实现

切入的类

package com.ccc.diy;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;

@Aspect //标注这个类是一个切面
public class AnnotationPointCut {
    @Before("execution(* com.ccc.service.UserServiceImpl.*(..))")
    public void before(){
        System.out.println("方法执行前------------");
    }
    @After("execution(* com.ccc.service.UserServiceImpl.*(..))")
    public void after(){
        System.out.println("方法执行后------------");
    }
    @Around("execution(* com.ccc.service.UserServiceImpl.*(..))")
    public void around(ProceedingJoinPoint jp) throws Throwable {
        System.out.println("环绕前");
        Signature signature = jp.getSignature();//获得签名
        System.out.println(signature);
        Object proceed = jp.proceed();//方法执行
        System.out.println("环绕后");
        System.out.println(proceed);
    }
}

xml

<?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-2.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd ">
    <!--注册bean-->
    <bean id="userService" class="com.ccc.service.UserServiceImpl"/>
    <bean id="log" class="com.ccc.log.Log"/>
    <bean id="afterLog" class="com.ccc.log.AfterLog"/>
    <!--方式一, 使用原生Spring API接口-->
    <!--方式二: 自定义类-->
    <!--方式三-->
    <bean id="anno" class="com.ccc.diy.AnnotationPointCut"/>
    <!--开启注解支持
           proxy-target-class=  JDK(默认)=false,  cglib=true-->
    <aop:aspectj-autoproxy/>
</beans>

顺序

环绕前
方法执行前------------
删除了一个用户
方法执行后------------
环绕后
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值