AOP的底层实现,动态代理和cglib代理
JDK动态代理
public Object proxy(Object target){
Object proxyInstance = Proxy.newProxyInstance(
MyJDKProxyTransactionManager.class.getClassLoader(),
target.getClass().getInterfaces(),
new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Object o = null;
try {
System.out.println("开启事物");
jdbcConnectionUtils.openTx();
o = method.invoke(target, args);
jdbcConnectionUtils.commitAndClose();
System.out.println("提交事物");
return o;
} catch (Exception e) {
e.printStackTrace();
jdbcConnectionUtils.rollbackAndClose();
}
return o;
}
}
);
return proxyInstance;
}
cglib代理
public static void main(String[] args) {
Enhancer enhancer = new Enhancer();
MyCar myCar = new MyCar();
enhancer.setSuperclass(myCar.getClass());
enhancer.setCallback(new MethodInterceptor() {
@Override
public Object intercept(Object proxy, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
Object o = null;
try {
System.out.println("cglib 代理前");
o = method.invoke(myCar, args);
System.out.println("cglib代理后");
return o;
} catch (Exception e) {
e.printStackTrace();
}
return o;
}
});
MyCar cglibCar = (MyCar) enhancer.create();
cglibCar.jump();
cglibCar.run();
}
你来是缘分,你走也是