一:
Spring AOP的默认代理方式是jdk动态代理,还有另外一种代理方式是cglib代理,简单说前者基于接口,后者基于继承,基本思路是将被代理对象的类作为父类,然后创建子类来进行方法的调用,调用的同时可以插入我们需要加入的方法。
二:
(1)pojo类
package net.wang.cglib; /** * User pojo类 * @author LiuRuoWang */ public class User { private Integer id; private String name; public void setId(Integer id) { this.id = id; } public Integer getId() { return id; } public void setName(String name) { this.name = name; } public String getName() { return name; } }
(2)接口UserService
package net.wang.cglib; public interface UserService { public void addUser(User user); public User getUser(int id); }
(3)实现类UserServiceImpl
package net.wang.cglib; public class UserServiceImpl implements UserService{ public void addUser(User user) { System.out.println("add User!"); } public User getUser(int id) { User user=new User(); user.setId(id); System.out.println("get User!"); return user; } }
(4)中间类CGProxy,需实现MethodInterceptor接口
package net.wang.cglib; 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 CGProxy implements MethodInterceptor{ //代理对象 private Object target; public CGProxy(Object target) { this.target=target; } public Object getProxyObject(){ Enhancer enhancer = new Enhancer(); //设置被代理对象类为父类 enhancer.setSuperclass(target.getClass()); //回调intercept方法 enhancer.setCallback(this); //创建代理对象 return enhancer.create(); } public Object intercept(Object arg0, Method arg1, Object[] arg2, MethodProxy arg3) throws Throwable { System.out.println("do sth before!"); Object result=arg3.invokeSuper(arg0, arg2); System.out.println("do sth after!"); return result; } }
(5)测试
package net.wang.cglib; public class CGProxyTest { public static void main(String[] args) { //被代理对象 Object proxyedObject = new UserServiceImpl(); CGProxy cgProxy = new CGProxy(proxyedObject); UserService proxyObject = (UserService) cgProxy.getProxyObject(); proxyObject.getUser(1); proxyObject.addUser(new User()); } }
以上代码继承接口,并不是代表着基于jdk动态代理方式,只是纯粹的面向接口编程,具体是哪种代理方式,还需看中间类的具体实现。
结果: