代理模式分為動(dòng)態(tài)代理和靜態(tài)代理
靜態(tài)代理:
- 定義一個(gè)人類的接口:Person
- 實(shí)現(xiàn)類:Student
- 代理類:StuProxy 實(shí)現(xiàn)Person 在重寫方法中調(diào)用Student,從而實(shí)現(xiàn)消息過(guò)濾,日志插入等AOP功能
動(dòng)態(tài)代理:
- JDK動(dòng)態(tài)代理
Student student = new Student();
Person person = (Person)Proxy.newProxyInstance(student.getClass().getClassLoader(), student.getClass().getInterfaces(), (proxy, method, params) -> {
System.out.println("做一個(gè)消息的過(guò)濾before");
method.invoke(student, params);
System.out.println("做一個(gè)消息的過(guò)濾after");
return null;
});
person.sayHello();
- 解釋: java.lang.reflect.Proxy創(chuàng)建一個(gè)代理對(duì)象
參數(shù)分三個(gè),第一個(gè)是classloader, 第二個(gè)接口數(shù)組,第三個(gè)是InvocationHandlerc增強(qiáng)invoke方法before, after可以寫自己的需要的方法 - 特點(diǎn):需要傳入接口,newProxyInstance通過(guò)接口的反射拿到方法名等屬性,在newProxyInstance定義中必須用接口模式,比較符合面向?qū)ο蟮乃枷?/li>
- 最終生成的代理類extend Proxy并實(shí)現(xiàn)了定義的傳入的接口
- CGLIB動(dòng)態(tài)代理
首先定義一個(gè)MyMethod自己的方法實(shí)現(xiàn)MethodInterceptor,增強(qiáng)intercept方法同理
static class MyMethod implements MethodInterceptor{
private Student stu;
public MyMethod(Student student){
stu = student;
}
@Override
public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
System.out.println(method);
System.out.println(objects.length);
System.out.println(methodProxy.getClass());
return methodProxy.invoke(stu, objects);
}
}
參數(shù)介紹:
- o 為對(duì)象
- method 調(diào)用的方法名
- objects為參數(shù)
- methodProxy:生成的代理對(duì)象的方法實(shí)例
method: public void com.firesoon.drgs.exe.test.Student.say()
objects為參數(shù): [Ljava.lang.Object;@31b7dea0
methodProxy: class net.sf.cglib.proxy.MethodProxy
pom.xml文件
<!--cglib -->
<dependency>
<groupId>cglib</groupId>
<artifactId>cglib</artifactId>
<version>3.2.4</version>
</dependency>
建議使用3.2.4 在3.2.6版本中new Enhancer()過(guò)程中出現(xiàn)包沖突的問(wèn)題
然后在調(diào)用
public static void main(String[] args) {
Student student = new Student();
Enhancer enhancer = new Enhancer();
enhancer.setSuperclass(student.getClass());
enhancer.setCallback(new MyMethod(student));
Student p = (Student)enhancer.create();
p.say();
}
- 根據(jù)實(shí)現(xiàn)類實(shí)現(xiàn)的代理的不需要傳入接口
- 代理類對(duì)象是由Enhancer類創(chuàng)建的。Enhancer是CGLIB的字節(jié)碼增強(qiáng)器
- superClass:實(shí)現(xiàn)類的class類生成二進(jìn)制字節(jié)碼文件,通過(guò)class對(duì)象反射出代理對(duì)象實(shí)例
- 在最后執(zhí)行的時(shí)候執(zhí)行的時(shí)候methodProxy.invoke();