AOP–代理对象–目标对象
使用Proxy创建代理对象:应用条件–目标对象必须实现接口
Proxy代理类:在JDK中反射的API中
使用JDK和CGlib创建代理对象,实现如下:
使用JDK创建代理对象需要实现接口,使用CGlib创建只需导入jar包即可
public class JDKProxyFactory implements InvocationHandler {
private Object targetObject;
public Object createProxyInstance(Object targerObject) {
this.targetObject = targerObject;
return Proxy.newProxyInstance(this.targetObject.getClass().getClassLoader(), this.targetObject.getClass().getInterfaces(), this);
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
PersonServiceBean bean = (PersonServiceBean) this.targetObject;
Object result = null;// 环绕通知
if (bean.getUser() != null) {
// ...advice()-->前置通知
try {
result = method.invoke(targetObject, args);
// -->后置通知
} catch (RuntimeException e) {
// -->例外通知
} finally {
// -->最终通知
}
}
return result;
}
}
//下面是测试类
public class AOPTest {
@BeforeClass
public static void setUpBeforeClass() throws Exception {
}
@Test
public void proxyTest() {
JDKProxyFactory factory = new JDKProxyFactory();
PersonService service = (PersonService) factory
.createProxyInstance(new PersonServiceBean("xxx"));
service.save("888");
}
@Test
public void proxyTest2() {
CGlibProxyFactory factory = new CGlibProxyFactory();
PersonServiceBean service = (PersonServiceBean) factory
.createProxyInstance(new PersonServiceBean("xxx"));
service.save("999");
}
}
public class CGlibProxyFactory implements MethodInterceptor {
private Object targetObject;
public Object createProxyInstance(Object targerObject){
this.targetObject = targerObject;
Enhancer enhancer = new Enhancer();
enhancer.setSuperclass(this.targetObject.getClass());//非final
enhancer.setCallback(this);
return enhancer.create();
}
@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){
result = methodProxy.invoke(targetObject, args);
}
return null;
}
}