SpringAop的optimize与proxyTargetClass有什么区别

在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的源码看一下他们的区别:

@Override
	public 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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值