如何使用spring的proxy-target-class属性

2025-04-20 00:40:22

1、为了说明下使用方式,首先列举下需要的测试类以及配置文件

如何使用spring的proxy-target-class属性

2、添加UserService接口类/*** 用户业务* Created by shaowei on 2017/7/31.*/public interface UserService { void addUser();}

如何使用spring的proxy-target-class属性

3、添加UserServiceImpl实现类/*** Created by shaowei on 2017/7/31.*/@Servicepublic class UserServiceImpl implements UserService { @Override public void addUser() { System.out.println("add user"); }}

如何使用spring的proxy-target-class属性

4、添加aop拦截处理类/*** 日志处理类* Create蟠校盯昂d by shaowei on 2017/7/31.*/@Componentpublic class LogHandler{ public void LogBefore() { System.out.println("Log before method"); } public void LogAfter() { System.out.println("Log after method"); }}

如何使用spring的proxy-target-class属性

5、spring配置文件applicatio艘绒庳焰nContext-test-aop.xml,添加激活注解和扫描注解配置,再添加aop配就女蒿鸳置<!-- 激活spring的注解. --><context:annotation-config /><context:component-scan base-package="cn.sw.study.common.test.spring.aop" /><aop:config proxy-target-class="true"> <aop:aspect id="log" ref="logHandler"> <aop:pointcut id="printLog" expression="execution(* cn.sw.study.common.test.spring.aop.service..*(..))" /> <aop:before method="LogBefore" pointcut-ref="printLog" /> <aop:after method="LogAfter" pointcut-ref="printLog" /> </aop:aspect></aop:config>

如何使用spring的proxy-target-class属性

6、添加AopTest测试类/*** AOP测试类* Created by shaowei on 201壅酪认奉7/7/31.*/public class AopTest { @Test public void testProxyTargetClass(){ ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext-test-aop.xml");// UserService userService = (UserService)context.getBean("userServiceImpl"); //proxy-target-class="true",为false时会报转换错误 UserServiceImpl userService = (UserServiceImpl)context.getBean("userServiceImpl"); userService.addUser(); }}

如何使用spring的proxy-target-class属性

7、运行测试类,查看结果,发现运行正常

如何使用spring的proxy-target-class属性

8、此时把proxy-target-class属性改成false或者去掉再次运行则报java.lang.ClassCastException: com.sun.proxy.$Proxy9 cannot be cast to cn.sw.study.common.test.spring.aop.service.UserServiceImpl错误

如何使用spring的proxy-target-class属性

9、如果使用这种方式获取bean,UserService userService = (UserService)context.getBean("userServiceImpl");则都不会报错,由此也可以发现,如果为false是基于接口做代理的,直接获取实现类进行类型转换,则会报代理类不能转换的错误

声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
猜你喜欢