- 基於cglib的動態代理,在spring的core包中添加了cglib支持,cglib是基於代理類是一個普通類,沒有接口的時候使用繼承父類(目標類)的方式來實現動態代理
public class MyBeanFartory {
public static UserService createUserService(){
final UserService userService = new UserService();
final MyAspect myAspect = new MyAspect();
//cglib生成代理對象的核心類
Enhancer enhancer = new Enhancer();
//確定父類
enhancer.setSuperclass(UserService.class);
//設置回調函數
enhancer.setCallback(new MethodInterceptor(){
@Override
public Object intercept(Object proxy, Method method, Object[] arg2, MethodProxy arg3) throws Throwable {
// TODO 自動生成的方法存根
//前
myAspect.before();
//執行目標方法
Object obj = method.invoke(userService, arg2);
//後
myAspect.after();
return obj;
}});
//創建代理類
UserService proxyUserService = (UserService) enhancer.create();
return proxyUserService;
}
}
- 基於jdk的動態代理,該方式需要目標類是實現接口的類
public class MyBeanFartory {
public static UserService createUserService(){
final UserService userService = new UserServiceImpl();
final MyAspect myAspect = new MyAspect();
UserService proxyService = (UserService)Proxy.newProxyInstance(MyBeanFartory.class.getClassLoader(),
userService.getClass().getInterfaces(),
new InvocationHandler(){
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
//前
myAspect.before();
Object obj = method.invoke(userService, args);
//後
myAspect.after();
return obj;
}});
return proxyService;
}
}