一:
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動態代理方式,只是純粹的面向接口編程,具體是哪種代理方式,還需看中間類的具體實現。
結果:
Spring AOP自定義注解方式實現日志管理 http://www.linuxidc.com/Linux/2015-11/125019.htm
Spring AOP進行日志記錄 http://www.linuxidc.com/Linux/2015-11/124731.htm
使用Spring AOP進行性能監控 http://www.linuxidc.com/Linux/2012-07/64681.htm
利用Spring AOP 更新Memcached 緩存策略的實現 http://www.linuxidc.com/Linux/2012-03/56503.htm
Spring AOP的兩種代理 http://www.linuxidc.com/Linux/2015-11/125017.htm
Spring AOP的注解實例 http://www.linuxidc.com/Linux/2015-11/125018.htm