动态代理
- 特点:字节码文件随用随创建,随用随加载。
- 作用:不用修改源码的基础上对方法增强。
- 分类:基于接口的动态代理,基于子类的动态代理。
基于接口的动态代理
- 涉及的类:Proxy
- 提供者:JDK官方
- 如何创建对象:使用Proxy类中的newProxyInstance方法
- 创建代理对象的要求:被代理类最少实现一个接口
- newProxyInstance方法的参数:
ClassLoader:类加载器
用于加载代理对象字节码,和被代理对象使用相同类加载器,固定写法。
Class[]:字节码数组
用于让代理对象和被代理对象有相同的方法,固定写法。
InvocationHandler:用于提供增强代码
让我们如何写代理,一般都是写一个该接口的实现类,通常情况下都是内部匿名类,但不是必须。此接口的实现类都是谁用谁写。
package com.yaku.proxy;
public class Producer implements IProducer{
@Override
public void saleProduct(float money) {
System.out.println("销售产品 获得金钱"+money);
}
@Override
public void afterService(float money) {
System.out.println("提供售后服务 获得金钱"+money);
}
}
package com.yaku.proxy;
public class Producer implements IProducer{
@Override
public void saleProduct(float money) {
System.out.println("销售产品 获得金钱"+money);
}
@Override
public void afterService(float money) {
System.out.println("提供售后服务 获得金钱"+money);
}
}
package com.yaku.proxy;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
public class Client {
public static void main(String[] args) {
final Producer producer = new Producer();
IProducer producerpoxy = (IProducer) Proxy.newProxyInstance(producer.getClass().getClassLoader(), producer.getClass().getInterfaces(),
new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Object returnValue = null;
if("saleProduct".equals(method.getName())){
Float money = (Float) args[0];
returnValue = method.invoke(producer,money*0.8f);
}
return returnValue;
}
});
producerpoxy.saleProduct(1000);
}
}
基于子类的动态代理
- 涉及的类:Enhancer
- 提供者:第三方cglib库
- 如何创建对象:使用Enhancer类中的create方法
- 创建代理对象的要求:被代理类不能是最终类
- create方法的参数:
Class:字节码
用于指定被代理对象的字节码。
Callback:用于提供增强代码
让我们如何写代理,一般都是写一个该接口的实现类,通常情况下都是内部匿名类,但不是必须。此接口的实现类都是谁用谁写。
一般写该接口的子接口实现类。:MethodIntercepto
package com.yaku.cglib;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;
import java.lang.reflect.Method;
public class Client {
public static void main(String[] args) {
final Producer producer = new Producer();
Producer cgligProducer = (Producer) Enhancer.create(producer.getClass(), new MethodInterceptor() {
@Override
public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
Object returnValue = null;
if("saleProduct".equals(method.getName())){
Float money = (Float) objects[0];
returnValue = method.invoke(producer,money*0.8f);
}
return returnValue;
}
});
cgligProducer.saleProduct(1000f);
}
}
AOP
- Joinpoint(连接点):是指那些被拦截到的点。在spring中,这些点是指方法,因为spring只支持方法类型的连接点。
- Pointcut(切入点):所谓切入点是指我们要对那些JoinPoint进行拦截的定义。
- Advice(通知/增强):是指拦截到Joinpoint之后要做的事情就是通知。
通知的类型:前置通知,后置通知,异常通知,最终通知,环绕通知:整个invoke方法执行就是环绕通知,有明确的切入点方法调用。 - Target(目标对象):代理的目标对象
- Weaving(织入):指把增强应用到目标对象来创建新的代理对象的过程。spring采用动态代理织入,而AspectJ采用编译器植入和类装载期织入。
- Proxy(代理):一个类被AOP织入增强后,就产生一个结果代理类。
- Aspect(切面):切入点和通知(引介)的结合。
package com.yaku.utils;
public class Logger {
public void beforePrintLog(){
System.out.println("前置通知Logger类中的beforePrintLog方法开始记录日志了。。。。");
}
public void afterReturningPrintLog(){
System.out.println("后置通知Logger类中的afterReturningLog方法开始记录日志了。。。。");
}
public void afterThrowingPrintLog(){
System.out.println("异常通知Logger类中的afterThrowingLog方法开始记录日志了。。。。");
}
public void afterPrintLog(){
System.out.println("最终通知Logger类中的afterLog方法开始记录日志了。。。。");
}
}
<?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.yaku.service.impl.AccountServiceImpl"/>
<bean id="logger" class="com.yaku.utils.Logger"/>
<aop:config>
<aop:pointcut id="pt1" expression="execution(public void com.yaku.service.impl.AccountServiceImpl.saveAccount())"/>
<aop:aspect id="logAdvice" ref="logger">
<aop:before method="beforePrintLog" pointcut-ref="pt1"/>
<aop:after-returning method="afterReturningPrintLog" pointcut="execution(public void com.yaku.service.impl.AccountServiceImpl.saveAccount())"/>
<aop:after-throwing method="afterThrowingPrintLog" pointcut="execution(public void com.yaku.service.impl.AccountServiceImpl.saveAccount())"/>
<aop:after method="afterPrintLog" pointcut="execution(public void com.yaku.service.impl.AccountServiceImpl.saveAccount())"/>
</aop:aspect>
</aop:config>
</beans>
package com.yaku.utils;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
@Component("logger")
@Aspect
public class Logger {
@Pointcut("execution(void com.yaku.service.impl.AccountServiceImpl.*())")
private void pt1(){
}
@Before("pt1()")
public void beforeLog(){
System.out.println("前置通知");
}
@AfterReturning("pt1()")
public void afterReturning(){
System.out.println("后置通知");
}
@AfterThrowing("pt1()")
public void afterThrowing(){
System.out.println("异常通知");
}
@After("pt1()")
public void afterLog(){
System.out.println("最终通知");
}
}