package com.qf.demo10.aop.cglib;
import java.lang.reflect.Method;
import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;
import org.springframework.lang.UsesJava7;
//使用cglib生成代理类对象
//生成代理对象,有目标类与切面类织入形成
public class MyBeanFactory {
public static UserServiceImpl getUserService() {
// 创建目标类对象
UserServiceImpl userService = new UserServiceImpl();
// 创建切面类对象
MyAspect myAspect = new MyAspect();
// 创建cglib核心类
Enhancer enhancer = new Enhancer();
/*
* 生成的代理与目标类之间什么关系?
* 继承关系 UserServiceImpl.class
*/
enhancer.setSuperclass(userService.getClass());
// 设置回调,MethodInterceptor与HandlerInvocation类似
enhancer.setCallback(new MethodInterceptor() {
/*
* 前三个参数与invoke方法一致
* MethodProxy:方法的代理
*/
@Override
public Object intercept(Object arg0, Method method, Object[] args, MethodProxy methodProxy)
throws Throwable {
// TODO Auto-generated method stub
myAspect.before();
//Object obj = method.invoke(userService, args);
//方法的代理,执行父类中的方法,就是目标类的
Object obj = methodProxy.invoke(userService, args);
myAspect.after();
return obj;
}
});
//生成代理对象
UserServiceImpl uImpl = (UserServiceImpl) enhancer.create();
return uImpl;
}
}