CGLIB动态代理
简单使用
还是最常见的例子,租客——中介——房东
代码中使用输出语句代替正真的业务!
首先,我们定义一个房东类。
public class Landlord{
public void deliver() {
try {
System.out.println("告知房东出租成功,房东收钱");
} catch (Exception e) {
e.printStackTrace();
System.out.println("出现异常,终止");
}
}
public void out() {
try {
System.out.println("告知房东,租客退房");
} catch (Exception e) {
e.printStackTrace();
System.out.println("出现异常,终止");
}
}
}
接下来创建一个类,实现org.springframework.cglib.proxy.MethodInterceptor
接口或net.sf.cglib.proxy.MethodInterceptor
接口,该类用来对原来的方法增强。(注意包,别导错)
依赖:自己选择,使用一个就行,我这里使用cglib
<dependency>
<groupId>cglib</groupId>
<artifactId>cglib</artifactId>
<version>3.3.0</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.0.8.RELEASE</version>
</dependency>
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;
import java.lang.reflect.Method;
public class CglibMethodInterceptor implements MethodInterceptor {
// 需要被代理的对象
private Object target;
public Object getTarget() {
return target;
}
public void setTarget(Object target) {
this.target