SpringAop的optimize与proxyTargetClass有什么区别

来源:互联网 发布:科比2012-13赛季数据 编辑:程序博客网 时间:2024/06/03 12:35

在SpringAop中如果要手动添加通知的话就会用到ProxyFactoryBean这个类:

<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"xmlns:context="http://www.springframework.org/schema/context"xsi:schemaLocation="        http://www.springframework.org/schema/beans        http://www.springframework.org/schema/beans/spring-beans.xsd        http://www.springframework.org/schema/tx        http://www.springframework.org/schema/tx/spring-tx.xsd        http://www.springframework.org/schema/aop        http://www.springframework.org/schema/aop/spring-aop.xsd        http://www.springframework.org/schema/context        http://www.springframework.org/schema/context/spring-context.xsd"><!-- 实现IUserService可继承SpringProxy类(继承后会通过cglib代理)--><bean id="userServiceImpl" class="com.tz.core.aop.UserServiceImpl"></bean><bean id="before" class="com.tz.core.aop.Before"></bean><bean id="proxy" class="org.springframework.aop.framework.ProxyFactoryBean"p:interceptorNames="before"p:target-ref="userServiceImpl"p:optimize="false"p:proxyTargetClass="false"></bean></beans>
userServiceImpl是目标对象,before是织入类(我同的是前置通知),proxy是我们的代理类:interceptorNames可以有多个值用逗号隔开、target-ref中放入目标对象。

optimize 和proxyTargetClass是设置是jdk的动态代理还是cglib的动态代理,接下来我们通过spring的源码看一下他们的区别:

@Overridepublic AopProxy createAopProxy(AdvisedSupport config) throws AopConfigException {if (config.isOptimize() || config.isProxyTargetClass() || hasNoUserSuppliedProxyInterfaces(config)) {Class<?> targetClass = config.getTargetClass();if (targetClass == null) {throw new AopConfigException("TargetSource cannot determine target class: " +"Either an interface or a target is required for proxy creation.");}if (targetClass.isInterface() || Proxy.isProxyClass(targetClass)) {return new JdkDynamicAopProxy(config);}return new ObjenesisCglibAopProxy(config);}else {return new JdkDynamicAopProxy(config);}}
这是创建代理类的方法,我们可以看出optimize和proxyTargetClass的作用是一样的只要设置一个就可以了,而hasNoUserSuppliedProxyInterfaces方法是判断SpringProxy是不是IUserService的父类。

所以如果optimize和proxyTargetClass都设置成false的话代理对象就要用IUserService承接,如果要用UserServiceImpl承接的话IUserService就要继承SpringProxy或者把optimize和proxyTargetClass其中之一设置成true。

0 0
原创粉丝点击