AOP是Spring的重要組成部分砾医,而AOP正是通過代理實現(xiàn)的拿撩。如果代理對象實現(xiàn)了接口,則默認(rèn)使用jdk動態(tài)代理如蚜,也可強制使用cglib代理压恒,如果未實現(xiàn)接口則只能使用cglib代理。
應(yīng)用:對一個操作前后事務(wù)的開啟和提交/回滾
靜態(tài)代理
public interface Fly {
void fly();
}
public class Bird implements Fly{
@Override
public void fly() {
// TODO Auto-generated method stub
System.out.println("飛啊飛~");
}
}
public class ProxyBird implements Fly{
//維護(hù)一個被代理對象
Fly bird;
public Fly getBird() {
return bird;
}
public void setBird(Fly bird) {
this.bird = bird;
}
@Override
public void fly() {
// TODO Auto-generated method stub
System.out.println("我代理增強一下你再飛~");
bird.fly();
}
}
public class TestBird {
public static void main(String[] args) {
Fly bird=new Bird();
ProxyBird proxyBird=new ProxyBird();
proxyBird.setBird(bird);
proxyBird.fly();
}
}
JDK動態(tài)代理
public interface UserDao {
void addUser();
}
public class UserDaoImpl implements UserDao{
@Override
public void addUser() {
// TODO Auto-generated method stub
System.out.println("添加用戶~");
}
}
public class TestJDK {
public static void main(String[] args) {
UserDao userDao=new UserDaoImpl();
UserDao proxy=(UserDao)Proxy.newProxyInstance(userDao.getClass().getClassLoader(), userDao.getClass().getInterfaces(), new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
// TODO Auto-generated method stub
System.out.println("invoke方法前做一些代理");
method.invoke(userDao, args);
System.out.println("invoke方法后做一些代理");
return proxy;
}
});
proxy.addUser();
}
}
CGLIB代理
public class UserService {
public void addUser(){
System.out.println("我不需要接口就可以被代理哦~");
}
}
public class Testcglb {
public static void main(String[] args) {
UserService userService=new UserService();
Enhancer enhancer = new Enhancer();
enhancer.setSuperclass(userService.getClass());
// 3错邦、設(shè)置回調(diào)函數(shù)
enhancer.setCallback(new MethodInterceptor() {
@Override
public Object intercept(Object proxy, Method method, Object[] args,
MethodProxy methodProxy) throws Throwable {
if(method.getName().equals("run")){
System.out.println("userService的add方法被攔截了探赫。。撬呢。伦吠。");
Object invoke = method.invoke(proxy, args);
System.out.println("真實方法攔截之后。魂拦。毛仪。。");
return invoke;
}
// 不攔截
return method.invoke(proxy, args);
}
});
UserService proxy = (UserService) enhancer.create();
proxy.run();
}
}