[英]Java - Spring AOP Pointcut not working
有人可以指出我在做什么錯嗎? 如何使我的Aspect運行?
我已經通過以下示例編寫了此代碼:
@Aspect
public class MethodLogger {
private Logger log = Logger.getLogger(getClass().getName());
@Pointcut("execution(* setHeight(..))")
public void log(JoinPoint point) {
log.info(point.getSignature().getName() + " called...");
}
}
我的簡單測試類:
public class ChairImpl implements Chair {
int height;
public ChairImpl(){}
public int getHeight() {
return height;
}
public void setHeight(int height) {
this.height = height;
}
}
我的Spring 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:p="http://www.springframework.org/schema/p"
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-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd"
default-destroy-method="destroy"
default-init-method="afterPropertiesSet"
default-autowire="byName"
>
<aop:aspectj-autoproxy>
<aop:include name="MethodLogger"/>
</aop:aspectj-autoproxy>
<bean id="logger1" class="lab.MethodLogger"/>
<bean id="chair1"
class="lab.test.ChairImpl"
>
<property name="height" value="10"/>
</bean>
</beans>
而我的主要方法是:
public class Main {
public static void main(String[] args){
ApplicationContext context = new ClassPathXmlApplicationContext("spec.xml");
((AbstractApplicationContext) context).close();
}
}
因此,在運行我的項目之前,Eclipse給了我這個錯誤(它將log
方法標記為紅色void
):
Pointcuts without an if() expression should have an empty method body
當我運行時,我的程序運行沒有錯誤,因為它看起來好像從未運行過log
方法。 那么我該如何解決它以便運行並輸出日志? 我只是嘗試從該方法打印test text
,但是它從未執行過,因此這意味着它永遠不會運行。 我在這里想念什么?
在文檔中,它只寫模糊的示例,例如:
@Pointcut("execution(* transfer(..))")// the pointcut expression
private void anyOldTransfer() {}// the pointcut signature
但是我發現很難理解如何實際使用它來查看結果。
您可以通過以下方式嘗試匿名切入點:
@Before("execution(* setHeight(..))")
public void log(JoinPoint point) {
log.info(point.getSignature().getName() + " called...");
}
或給切入點起一個名字並以這種方式使用它:
@Pointcut("execution(* setHeight(..))")
public void setters() {}
@Before("setters()")
public void log(JoinPoint point) {
...
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.