[英]Spring AOP @Pointcut not triggering
我想在调用另一个类中的特定方法时触发一个方法,这就是为什么我想到使用@Pointcut的原因。
下面的代码与我正在编码的代码几乎相同,而我不必添加其他内容。
public class OrgManagerImpl implements OrgManager {
public IOrg getOrg(String orgShortName) {
}
}
这是应该触发的类:
@Aspect
public class OrgManagerSynchronizer {
@Pointcut("execution(* com.alvin.OrgManager.getOrg(..))")
public void classMethods() {}
@Before("classMethods()")
public void synchronize(JoinPoint jp) {
//code should be executed. but does not execute.
}
}
在我的.xml文件中指定了:
aop:aspectj-autoproxy
我还应该添加什么? 接下来做什么?
检查以下内容。
1)检查OrgManagerImpl是否在上下文xml中被定义为bean,或者在您具有的XML或该类的包中被标记为@Component&。
2)如果以上内容正确,请尝试如下更改切入点
@Pointcut("execution(* get*(..))")
该切入点拦截所有get方法。 看看这时您的同步方法是否有效。 如果可以,那么至少您的弹簧配置可以。 您只需要优化切入点表达式。 但是,如果这还是行不通,那么您的spring aop配置本身就有问题,因此我们可以集中精力解决这些问题。
另外,如果这不起作用,则尝试提供更多信息,例如上下文XML,Bean Java类等。
您需要检查两件事。
以下是我的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"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
<aop:aspectj-autoproxy/>
<context:component-scan base-package="com.techoffice"/>
<bean class="com.techoffice.example.ExampleAspect"/>
</beans>
ExampleAspect.java
package com.techoffice.example;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
@Aspect
public class ExampleAspect {
@Pointcut("execution (* com.techoffice..*(..))")
public void anyRun() {}
@Before(value="anyRun()")
public void beforeAnyRun(JoinPoint jointPoint){
System.out.println("Before " + jointPoint.getClass().getName() + "." + jointPoint.getSignature().getName());
}
@After(value="anyRun()")
public void afterAnyRun(JoinPoint jointPoint){
System.out.println("After " + jointPoint.getClass().getName() + "." + jointPoint.getSignature().getName());
}
}
HelloWorldExample
package com.techoffice.example;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Component;
@Component
public class HelloWorldExample {
public void run(){
System.out.println("run");
}
public static void main(String[] args){
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
HelloWorldExample helloWorldExample = context.getBean(HelloWorldExample.class);
helloWorldExample.run();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.