仔细想想SpringAOP也不难嘛,面试没有必要慌
2021-04-13 21:29
import com.mylifes1110.service.LandlordService; import java.lang.reflect.Method; /** public class ProxyTest {package com.mylifes1110.advice3;
import com.mylifes1110.service.impl.LandlordServiceImpl;
import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.InvocationHandler;
* @ClassName ProxyTest
* @Description CGLIB动态代理实现
* @Author Ziph
* @Date 2020/7/19
* @Since 1.8
* @Version 1.0
*/
public static void main(String[] args) {
final LandlordService landlordService = new LandlordServiceImpl();
// 创建字节码增强对象
Enhancer enhancer = new Enhancer();
// 设置父类(等价于实现原始类接口)
enhancer.setSuperclass(landlordService.getClass());
// 设置回调函数(额外功能代码)
enhancer.setCallback(new InvocationHandler() {
@Override
public Object invoke(Object o, Method method, Object[] objects) throws Throwable {
// 代理事件
System.out.println("发布消息");
System.out.println("看房子");
Object ret = method.invoke(landlordService, args);
return ret;
}
});
// 创建动态代理类
LandlordService proxy = (LandlordService) enhancer.create();
proxy.rent();
/**
* 结果:
*
* 发布消息
* 看房子
* 签合同
* 收款
*/
}
}
文章标题:仔细想想SpringAOP也不难嘛,面试没有必要慌
文章链接:http://soscw.com/index.php/essay/75372.html