2014-01-17 116 views
0

有人可以指出我做錯了什麼嗎?我怎樣才能讓我的方面運行?Java - Spring AOP切入點不起作用

我寫了這個代碼下面的一些例子:

@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的給我這個錯誤(這標誌着紅色voidlog法):

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 

但我覺得很難理解如何實際使用它看到的結果。

+2

你只有方面的一部分。你有什麼地方,但想念什麼時候(周圍,之前等)。在切入點旁邊(應始終使用一個emtpy方法),您還需要一個表示建議的方法。即一個用'@ Before'註解的方法。 –

回答

1

你可以試試匿名切入點是這樣的:

@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) { 
... 
} 
+0

謝謝,這有幫助。 – Andrius