Spring AOP - 方法invoke()不会发生

时间:2012-08-09 09:08:58

标签: java spring aop

我有一个default-context.xml

<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:security="http://www.springframework.org/schema/security"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
                    http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-2.0.4.xsd">
<!-- some other beans -->
<bean id="licenseTestingAdvice" class="mypackage.LicenseTestingAdvice" />
<bean id="jdbcTemplate" class="mypackage.ProxyFactoryBean">
    <property name="interceptorNames">
        <list>
            <idref bean="licenseTestingAdvice" />
        </list>
    </property>
    <property name="target">
        <value>mypackage.JDBCTemplate</value>
    </property>
    <property name="proxyTargetClass" value="true" />
</bean>

LicenseTestingAdvice.java:

import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;

import java.lang.reflect.Method;

public class LicenseTestingAdvice implements MethodInterceptor {
    @Override
    public Object invoke(MethodInvocation inv) throws Throwable {
        Method method = inv.getMethod();

        System.out.println(String.format(">> Method %s was called before", method.getName()));
        inv.proceed();
        System.out.println(String.format(">> Method %s was called after", method.getName()));

        return null;  //To change body of implemented methods use File | Settings | File Templates.
    }
}

当我调用JDBCTemplate类的execute()方法时 - 不调用invoke()方法。如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

这个<value>mypackage.JDBCTemplate</value>应该是对bean或内部bean的引用。此外,拦截器名称应该是bean的名称,而不是对它的引用。类似的东西:

<bean id="myJdbcTemplate" class="mypackage.JDBCTemplate"/>
<bean id="jdbcTemplate" class="mypackage.ProxyFactoryBean">
    <property name="interceptorNames">
        <list>
            <value>licenseTestingAdvice</value>
        </list>
    </property>
    <property name="target" ref="myJdbcTemplate"/>
    <property name="proxyTargetClass" value="true" />
</bean>