[英]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.