Spring中代理模式的学习
使用jdk动态代理
UserService proxyService=(UserService)Proxy.newProxyInstance(MyBeanFactory.class.getClassLoader(),
service.getClass().getInterfaces(),
new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
aspect.before();
Object obj=method.invoke(service,args);
aspect.after();
return obj;
}
});
newProxyInstance的参数:
真实对象.getClass().getClassLoader() //类加载器
接口对象.getClass().getClassLoader() //接口数组
new InvocationHandler() //处理器
public Object invoke的参数
proxy //代理对象
method //代理对象的方法被封装成的对象
args //代理对象在调用方法时,传递的实际参数
使用cglib增强字节码
Enhancer enhancer = new Enhancer();
enhancer.setSuperclass(service.getClass()); //设置父类
enhancer.setCallback(new MethodInterceptor() {//设置回调(拦截)
/*
proxy:是拦截接口的子类
*/
@Override
public Object intercept(Object proxy, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
aspect.before();
Object obj=methodProxy.invokeSuper(proxy,args);
aspect.after();
return obj;
}
});
UserServiceImpl proxy=(UserServiceImpl)enhancer.create();
return proxy;
Spring编写代理(半自动)
xml文件
<bean id="userService" class="cn.sky.Service.UserServiceImpl"/>
<bean id="Aspect" class="cn.sky.aspect.MyAspect02"/>
<bean id="proxyService" class="org.springframework.aop.framework.ProxyFactoryBean">
<property name="interfaces" value="cn.sky.Service.UserService"/>
<property name="target" ref="userService"/>
<property name="interceptorNames" value="Aspect"/>
<property name="optimize" value="true"/>
切面类
public class MyAspect02 implements MethodInterceptor {
@Override
public Object invoke(MethodInvocation methodInvocation) throws Throwable {
System.out.println("执行代码前");
//proceed:行进
Object obj=methodInvocation.proceed();
System.out.println("执行代码后");
return obj;
}
}