CGLIB动态代理能代理拥有父类的子类
CGLIBProxy类
public class CGLIBProxy implements MethodInterceptor {
private Object target;// 被代理对象
public Object CreateCGLIBProxy(Object target) {
this.target = target;
Enhancer enhancer = new Enhancer();
// 设置父类
enhancer.setSuperclass(target.getClass());
// 设置回调函数
enhancer.setCallback(this);
// 创建子类(代理对象)
return enhancer.create();
}
/**
* obj 代理对象
* method 被代理对象的方法
* args 被代理对象的参数
*/
public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {
check();
// 执行被代理对象的方法
Object invoke = method.invoke(target, args);
log();
return invoke;
}
//用户添加或者删除前需要检查是否有权限操作
public void check(){
System.out.println("权限检查通过...");
}
//用户删除后需要记录日志
public void log(){
System.out.println("日志记录成功...");
}
}
applicationContext.xml
<!--创建CGLIBProxy代理对象-->
<bean id="cglibproxy" class="com.msb.cglib.CGLIBProxy"/>
UserAdd类
public abstract class UserAdd {
public void add() { };
}
UserAddSub类
public class UserAddSub extends UserAdd {
@Override
public void add() {
System.out.println("用户添加...");
}
}
测试类
public class ProxyTest {
ApplicationContext app;
@Before
public void init(){
//加载配置文件
app = new ClassPathXmlApplicationContext("applicationContext.xml");
}
@Test
public void test3() {
CGLIBProxy cg = (CGLIBProxy)app.getBean("cglibproxy");
UserAdd user = (UserAdd)cg.CreateCGLIBProxy(new UserAddSub());
user.add();
}
}
运行结果