注释:
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD})
public @interface DeadlockRetry {
}
拦截器:
public class DeadlockRetryMethodInterceptor implements MethodInterceptor
{
@Override
public Object invoke(MethodInvocation invocation) throws Throwable
{
System.err.println("I've been Intercepted!");
return invocation.proceed();
}
}
截获类:
public class Intercepted {
@DeadlockRetry
public void interceptMe()
{
System.err.println("Above here should be a message I've been Intercepted!");
}
}
主要起点:
public class Main {
public static void main(String[] args)
{
//Function that loads the spring-context.xml
SpringContext.init();
Intercepted intercepted = new Intercepted();
intercepted.interceptMe();
}
}
spring-context.xml:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
classpath:/org/springframework/beans/factory/xml/spring-beans-3.2.xsd
http://www.springframework.org/schema/tx
classpath:/org/springframework/transaction/config/spring-tx-3.2.xsd
http://www.springframework.org/schema/aop
classpath:/org/springframework/aop/config/spring-aop-3.2.xsd
http://www.springframework.org/schema/context
classpath:/org/springframework/context/config/spring-context-3.2.xsd">
<aop:aspectj-autoproxy />
<context:annotation-config/>
<bean id="deadlockRetryAdvice" class="com.metaregistrar.hibernate.DeadlockRetryMethodInterceptor"/>
<bean id="deadlockPointcutAdvisor" class="org.springframework.aop.support.DefaultPointcutAdvisor">
<property name="advice" ref="deadlockRetryAdvice"/>
<property name="pointcut" ref="deadlockRetryPointcut"/>
</bean>
<bean name="deadlockRetryPointcut" class="org.springframework.aop.support.annotation.AnnotationMatchingPointcut">
<constructor-arg index="0" value="com.metaregistrar.hibernate.DeadlockRetry"/>
<constructor-arg index="1" value="com.metaregistrar.hibernate.DeadlockRetry"/>
</bean>
</beans>
Stderr结果:
上面应该是我被截获的消息!
预期的Stderr结果:
我被拦截了! 上面应该是我被截获的消息!
我做错了什么?我一整天都在解决这个问题,而且它变得很烦人......
答案 0 :(得分:1)
Spring AOP仅适用于spring bean。您应该在spring配置文件中将截取的对象定义为bean,从上下文中获取它并在其上调用方法。
这是不正确的部分。
Intercepted intercepted = new Intercepted();
intercepted.interceptMe();
将其添加到xml文件中
然后从spring ctx
中检索实例ApplicationContext ctx = // create context using the config file
intercepted = ctx.getBean("intercepted",Intercepted.class);
intercepted.interceptMe();