1、基于接口和子类的动态代理
1.1基于接口的动态代理
直接上代码,首先有一个接口:
package proxy;
/**
* @author :
* @date :Created in 2020/5/19 上午11:27
* @description:${description}
* @modified By:
* @version: $version$
*/
public interface IProducer {
/**
* 销售产品
* @param money
*/
public void saveProduct(Double money);
/**
* 产品售后
* @param money
*/
public void afterService(Double money);
}
然后有一个该接口的实现类:
package proxy;
/**
* @author :
* @date :Created in 2020/5/19 上午11:26
* @description:生产者
* @modified By:
* @version: $version$
*/
public class Producer implements IProducer{
public void saveProduct(Double money) {
System.out.println("销售产品,并拿到钱"+money);
}
public void afterService(Double money) {
System.out.println("产品售后,并拿到钱"+money);
}
}
那我们现在想的是,如何在不改变接口方法的源码基础上,对方法进行增强,然后我们需要创建一个代理对象:
package proxy;
import com.sun.org.apache.bcel.internal.generic.NEW;
import org.omg.PortableServer.POAPackage.InvalidPolicy;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
/**
* @author :
* @date :Created in 2020/5/19 上午11:27
* @description:消费者
* @modified By:
* @version: $version$
*/
public class Consumer{
public static void main(String args[]){
final Producer producer = new Producer();//producer即是被代理对象
/**
* 动态代理的特点:
* 特点:字节码随用随创建,随用随加载
* 作用:不修改源码的基础上,对方法增强
* 分类:
* 1、基于接口的动态代理
* 2、基于子类的动态代理
* 基于接口的动态代理:
* 涉及的类:Proxy
* 提供者:JDK官方
* 如何创建代理对象:
* 使用Proxy类中newProxyInstance方法
* 创建代理对象的要求:
* 被代理对象至少实现一个接口,如果没有则不能使用
* newProxyInstance方法参数:
* Classloader:类加载器
* 加载代理对象的字节码,和被代理对象使用相同的类加载器。固定写法
* Class[]:字节码数组
* 用于让代理对象和被代理对象有相同的方法
* InvovationHandler:用于提供增强的代码
* 让我们如何写代理,一般都是一个该接口的实现类,通常是匿名内部类,但不是必须的
* 此接口的实现类,都是谁用谁写
*/
//通过Proxy.newProxyInstance创建的即是代理对象
IProducer proxyProducer = (IProducer) Proxy.newProxyInstance(producer.getClass().getClassLoader(), producer.getClass().getInterfaces(),
new InvocationHandler() {
/**
* 作用,执行被代理对象的任何接口方法都会经过该方法
* @param proxy 代理对象的引用
* @param method 当前执行的方法
* @param args 当前执行方法所需的参数
* @return 和被代理对象方法有相同的返回值
* @throws Throwable
*/
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Object objValue = null;
//提供增强的代码
//1、获取方法参数
Double money = (Double) args[0];
//2、判断当前方法是不是销售
if("saveProduct".equals(method.getName())) {
objValue = method.invoke(producer,money*0.8);
}
return objValue;
}
});
proxyProducer.saveProduct(10000.00);
}
}
1.2基于子类的动态代理
首先有一个被代理类:
package sunClass;
import proxy.IProducer;
/**
* @author :
* @date :Created in 2020/5/19 上午11:26
* @description:生产者
* @modified By:
* @version: $version$
*/
public class Producer {//implements IProducer{
public void saveProduct(Double money) {
System.out.println("销售产品,并拿到钱"+money);
}
public void afterService(Double money) {
System.out.println("产品售后,并拿到钱"+money);
}
}
然后创建一个代理类:
package sunClass;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;
import proxy.IProducer;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
/**
* @author :
* @date :Created in 2020/5/19 上午11:27
* @description:消费者
* @modified By:
* @version: $version$
*/
public class Consumer{
public static void main(String args[]){
final Producer producer = new Producer();
/**
* 动态代理的特点:
* 特点:字节码随用随创建,随用随加载
* 作用:不修改源码的基础上,对方法增强
* 分类:
* 1、基于接口的动态代理
* 2、基于子类的动态代理
* 基于子类的动态代理:
* 涉及的类:Enhancer
* 提供者:第三方cglib库
* 如何创建代理对象:
* 使用Enhancer类中create方法
* 创建代理对象的要求:
* 被代理对象不能是最终类
* create方法参数:
* class:字节码
* 用于指定被代理对象的字节码
* callback:用于提供增强的代码
* 让我们如何写代理,一般都是一个该接口的实现类,通常是匿名内部类,单不是必须的
* 此接口的实现类,都是谁用谁写
* 该接口的子接口实现类,MethodInterceptor
*/
Producer cglibProducer = (Producer) Enhancer.create(producer.getClass(), new MethodInterceptor() {
/**
* 执行被代理对象的任何方法都会经过该方法
* @param o 代理对象的引用
* @param method 当前执行的方法
* @param objects 当前执行方法所需的参数
* @param methodProxy 当前执行方法的代理对象
* @return
* @throws Throwable
*/
public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
Object objvalue = null;
//1、获取方法的参数
Double money = (Double) objects[0];
//2、判断方法是否是售后
if("afterService".equals(method.getName())){
objvalue = method.invoke(producer,money*0.5);
}
return objvalue;
}
});
cglibProducer.afterService(10000.00);
}
}
2、基于xml的AOP配置
AOP的根本目的就是在不改变业务层接口方法的基础上,对业务层的方法进行增强。
首先创建一个maven工程,导入依赖的坐标:
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.0.2.RELEASE</version>
</dependency>
<!--解析切入点表达式-->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.7</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.0.2.RELEASE</version>
</dependency>
</dependencies>
然后创建导入spring AOP的约束文件内容,创建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.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">
<bean id="accountService" class="com.yunxiao.service.impl.AccountImplService"></bean>
<!--整个的过程首先有一个业务层的对象,然后需要对业务层对象里面的方法进行日志打印,Logger对象具备打印日志的功能。
所以,首先配置一个切面,然后把具备打印日志功能的Logger对象交给切面进行管理,需求是在业务方法执行之前打印日志,
所以配置的通知类型是aop:before,前置通知的方法是printLog,切入点表达式标示类对哪个方法进行加强-->
<!--spring aop配置的配置步骤
1、把通知的bean也交给spring来管理
2、用aop:config标签表明Aop的配置开始
3、使用aop:asepct表明配置切面
id属性:给切面提供唯一标示
ref属性:表示通知类bean的id
4、在aop:asepect内部使用对应标签配置通知类型
现在市容printLog方法在切入点之前执行,属于前置通知
aop:before 前置通知
method:哪个方法是前置通知
pointcut属性:用于指定切入点表达式,该切入点表示式对哪些方法进行加强
切入点表示式写法:
关键字:execution(表达式)
表达式:
修饰符.返回值.包名.类名.方法名(参数列表)
标准写法:public void com.yunxiao.service.impl.AccountImplService.saveAccount()
全通配写法:
* *..*.*(..)
访问修饰符可以省略
void com.yunxiao.service.impl.AccountImplService.saveAccount()
返回值可以使用通配符
* com.yunxiao.service.impl.AccountImplService.saveAccount()
包名可以使用*代替,有几层就需要写几层,可以使用*..匹配任意层级的包
* *.*.*.*.AccountImplService.saveAccount()
类名称可以使用*代替,匹配任意的类
* *.*.*.*.*.saveAccount()
方法名称可以使用*代替,匹配任意的无参方法
* *.*.*.*.*.*()
参数也可以使用*代替,一个*代表一个参数,也可以直接写参数类型,基本类型直接写,应用类型写全限定类名
* *.*.*.*.*.*(*)
* *.*.*.*.*.*(int)
参数可以使用..匹配任意的参数
* *.*.*.*.*.*(..)
实际开发中的通常写法:
* com.yunxiao.service.impl.*.*(..)-->
<bean id="logger" class="com.yunxiao.com.yunxiao.utils.Logger"></bean>
<!--配置AOP-->
<aop:config>
<!--配置切面-->
<aop:aspect id="logAdvice" ref="logger">
<!--配置通知类型,并建立通知方法和切入点方法的关联-->
<aop:before method="printLog" pointcut="execution(* com.yunxiao.service.impl.*.*(..))"></aop:before>
</aop:aspect>
</aop:config>
</beans>
AOP的切入点表达式和环绕通知:
<?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
http://www.springframework.org/schema/aop/spring-aop.xsd">
<bean id="accountService" class="com.yunxiao.service.impl.AccountServiceImpl"></bean>
<bean id="logger" class="com.yunxiao.com.yunxiao.utils.Logger"></bean>
<aop:config>
<!--配置切入点表达式,id属性用于指定表达式的唯一标示,expression用于指定表达式的内容
此标签写在aop:asepect标签里面只能在当前切面使用
也可以写在aop:asepect标签外面,所有切面都可使用,根据约束只能写在aop:asepct标签前面-->
<aop:pointcut id="pt1" expression="execution(* com.yunxiao.service.impl.*.*(..))"></aop:pointcut>
<aop:aspect id="loggerAdvice" ref="logger">
<!--配置前置通知,在切入点方法执行之前执行
<aop:before method="beforePrintLogger" pointcut-ref="pt1"></aop:before>-->
<!--配置后置通知,在切入点方法正常执行之后执行
<aop:after-returning method="afterRuntimePrintLogger" pointcut-ref="pt1"></aop:after-returning>-->
<!--配置异常通知,在切入点方法产生异常之后执行
<aop:after-throwing method="afterThrowingPrintLogger" pointcut-ref="pt1"></aop:after-throwing>-->
<!--配置最终通知,不管切入点方法是否正常执行它都会在其后执行
<aop:after method="afterPrintLogger" pointcut-ref="pt1"></aop:after>-->
<!--配置环绕通知-->
<aop:around method="aroundPrintlog" pointcut-ref="pt1"></aop:around>
</aop:aspect>
</aop:config>
</beans>
3、基于注解的AOP配置
pom坐标和基于xml的相同
配置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"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!--配置spring创建容器时扫描的包-->
<context:component-scan base-package="com.yunxiao"></context:component-scan>
<!--配置springAOP开启注解的支持-->
<aop:aspectj-autoproxy></aop:aspectj-autoproxy>
</beans>
代理类
package com.yunxiao.utils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
/**
* @author :
* @date :Created in 2020/5/19 下午11:48
* @description:使用注解时,第一步执行的Before、第二步执行after、第三步执行afterReturnning或者afterThrowing
* @modified By:
* @version: $version$
*/
@Component("logger")
@Aspect//表示当前类是一个切面类
public class Logger {
@Pointcut("execution(* com.yunxiao.service.impl.*.*(..))")
public void pt1(){}
/**
* 前置通知
*/
@Before("pt1()")
public void beforePrintLogger(){
System.out.println("前置通知Logger开始打印beforeprintLogger日志。。。");
}
/**
* 后置通知
*/
@AfterReturning("pt1()")
public void afterRuntimePrintLogger(){
System.out.println("后置通知Logger开始打印afterRuntimePrintLogger日志。。。");
}
/**
* 异常通知
*/
@AfterThrowing("pt1()")
public void afterThrowingPrintLogger(){
System.out.println("异常通知Logger开始打印afterThrowingPrintLogger日志。。。");
}
/**
* 最终通知
*/
@After("pt1()")
public void afterPrintLogger(){
System.out.println("最终通知Logger开始打印afterPrintLogger日志。。。");
}
/**
* 环绕通知
* 问题:配置了环绕通知以后,切入点方法没有执行,通知方法执行了
* 通过对比动态代理中的环绕通知方法,发现动态代理中的环绕通知有明确的切入点方法(业务方法)调用,而我们没有
* 解决:Spring提供了一个接口:ProceedingjoinPoint,该接口有一个proceed()方法,此方法就相当于明确切入点,
* 该接口可以作为环绕通知的方法参数,在程序执行时,spring框架会为我们提供该接口的实现类供我们使用
*
* Spring环绕通知:
* 环绕通知是spring我们提供的一种可以在代码中手动控制增强方法何时执行的方式
*/
//@Around("pt1()")
public void aroundPrintlog(ProceedingJoinPoint pdp){
try {
Object args[] = pdp.getArgs();//得到该方法的参数
System.out.println("环绕通知Logger开始打印aroundPrintlog日志。。。前置");
pdp.proceed(args);//明确调用业务层方法(切入点方法)
System.out.println("环绕通知Logger开始打印aroundPrintlog日志。。。后置");
}catch (Throwable t){
System.out.println("环绕通知Logger开始打印aroundPrintlog日志。。。异常");
}finally {
System.out.println("环绕通知Logger开始打印aroundPrintlog日志。。。最终");
}
}
}