动态代理

基于jdk的动态代理和基于cglib的动态代理实现方式。

基于jdk的动态代理(有接口)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
//接口
public interface User {
void save();
}

//被代理类
class UserImpl implements User{
public void save(){
System.out.println("save running......");
}
}

//增强方法
class UserAdvice{
public void before(){
System.out.println("before save");
}

public void after(){
System.out.println("after save");
}
}

//代理工厂类
class ProxyFactory{
public static Object getProxy(){
MyInvocationHandler handler = new MyInvocationHandler();
//被代理对象
User user = new UserImpl();
//增强对象
UserAdvice userAdvice = new UserAdvice();
handler.setAdvice(userAdvice);
handler.setObj(user);
//返回代理对象
return Proxy.newProxyInstance(user.getClass().getClassLoader(),
user.getClass().getInterfaces(),handler);
}
}

class MyInvocationHandler implements InvocationHandler{
//被代理对象
private Object obj;
public void setObj(Object obj){
this.obj = obj;
}
//增强对象
private UserAdvice advice;
public void setAdvice(UserAdvice advice){
this.advice = advice;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
advice.before();
Object invoke = method.invoke(obj, args);
advice.after();
return invoke;
}
}

//测试
class Test{
public static void main(String[] args) {
User proxy = (User) ProxyFactory.getProxy();
proxy.save();
}
}

基于cglib的动态代理(无接口)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
//被代理对象
public class Target {

public void save(){
System.out.println("save running......");
}
}
//增强
class Advice{
public void before(){
System.out.println("save before");
}

public void after(){
System.out.println("save after");
}
}

class Test{
public static void main(String[] args) {
Target target = new Target();
Advice advice = new Advice();
//创建增强器
Enhancer enhancer = new Enhancer();
//设置父类(被代理类)
enhancer.setSuperclass(Target.class);
//设置回调
enhancer.setCallback(new MethodInterceptor() {
@Override
public Object intercept(Object o, Method method, Object[] objects,
MethodProxy methodProxy) throws Throwable {
//执行前置
advice.before();
//执行目标
Object invoke = method.invoke(target, args);
//执行后置
advice.after();
return invoke;
}
});
//创建代理对象
Target proxy = (Target) enhancer.create();
proxy.save();
}
}
Author

叶润繁

Posted on

2022-02-08

Licensed under