import java.lang.reflect.Method;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;
public class CGlibProxyFactory implements MethodInterceptor{
private Object targetObject;
public Object createProxyIntance(Object targetObject){
this.targetObject = targetObject;
Enhancer enhancer = new Enhancer();
//继承了目标类,覆盖非final方法,代理类是目标类的子类
enhancer.setSuperclass(this.targetObject.getClass());//
//设置回调
enhancer.setCallback(this);//回调intercept
return enhancer.create();
}
/**
* proxy:目标对象本身
* method:拦截到的方法
* args:方法的输入参数
* methodProxy:方法的代理对象
*/
@Override
public Object intercept(Object proxy, Method method, Object[] args,
MethodProxy methodProxy) throws Throwable {
PersonServiceBean bean = (PersonServiceBean) this.targetObject;
Object result = null;
if(bean.getUser()!=null){
method.invoke(targetObject, args);
}
return result;
}
}
无须实现接口
public class PersonServiceBean {
private String user = null;
public PersonServiceBean(){
}
public String getUser() {
return user;
}
public PersonServiceBean(String user){
this.user = user;
}
public String getPersonName(Integer personId) {
System.out.println("我是 getPersonName方法");
return "salyfan";
}
public void save(String name) {
System.out.println("我是save()方法");
}
public void update(String name, Integer personId) {
System.out.println("我是update()方法");
}
}
@Test
public void aopCGlibProxyFactory(){
CGlibProxyFactory factory = new CGlibProxyFactory();
PersonServiceBean service = (PersonServiceBean) factory.
createProxyIntance(new PersonServiceBean("fan"));
service.save("fanf");
}