Spring 的Advisor注入可以根据接口注入,也可以按照实体类进行注入
1.根据接口注入
XML配置文件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id="executeMethodAdvisor" class="org.springframework.aop.support.NameMatchMethodPointcutAdvisor">
<property name="mappedNames">
<list>
<value>execute</value>
</list>
</property>
<property name="advice">
<ref bean="afterExecuteAdvice"/>
</property>
</bean>
<bean id="afterExecuteAdvice" class="advisor.AfterExecuteAdvice">
</bean>
<bean id="targetBeanTarget" class="advisor.TargetBean">
</bean>
<bean id="proxyBean" class="org.springframework.aop.framework.ProxyFactoryBean">
<property name="proxyInterfaces">
<list>
<value>advisor.TargetInterface</value>
</list>
</property>
<property name="interceptorNames">
<list>
<value>executeMethodAdvisor</value>
</list>
</property>
<property name="target">
<ref bean="targetBeanTarget"/>
</property>
</bean>
</beans>
Java文件
public class TargetBean implements TargetInterface{
public void execute(){
...
}
}
2. 根据具体类注入,只需把上边的<property name="proxyInterfaces">去掉,同时令TargetBean不实现接口即可。
xml文件
<bean id="targetBean" class="org.springframework.aop.framework.ProxyFactoryBean">
<property name="interceptorNames">
<list>
<value>executeMethodAdvisor</value>
</list>
</property>
<property name="target">
<ref bean="targetBeanTarget"/>
</property>
</bean>
Java文件
public class TargetBean {
public void execute(){
...
}
}
注意,这种情况必须引入cglib-nodep.jar,否则抛出异常
Cannot proxy target class because CGLIB2 is not available. Add CGLIB to the class path or specify proxy interfaces.
异常原因可在org.springframework.aop.framework。DefaultAopProxyFactory中找到
public class DefaultAopProxyFactory implements AopProxyFactory, Serializable {
/** Whether the CGLIB2 library is present on the classpath */
private static final boolean cglibAvailable =
ClassUtils.isPresent("net.sf.cglib.proxy.Enhancer", DefaultAopProxyFactory.class.getClassLoader());
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()) {
return new JdkDynamicAopProxy(config);
}
if (!cglibAvailable) {
throw new AopConfigException(
"Cannot proxy target class because CGLIB2 is not available. " +
"Add CGLIB to the class path or specify proxy interfaces.");
}
return CglibProxyFactory.createCglibProxy(config);
}
else {
return new JdkDynamicAopProxy(config);
}
}
......
}
因为没有找到net.sf.cglib.proxy.Enhancer