在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。