Spring中的代理模式

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;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值