2015-09-28 76 views
5

的所有方法我使用AOP首次。 我寫了下面的AOP代碼,當我使用它來截取特定的方法時,它工作正常。AOP在一個包

有人可以指導我 - 我怎麼可以將它設置攔截在一定的包裝(com.test.model)的所有方法?

基本上如何設置appcontext.xml。

而且,做我需要做類似下面調用每個方法之前打電話?

AopClass aoptest = (AopClass) _applicationContext.getBean("AopClass"); 
aoptest.addCustomerAround("dummy"); 

有人可以幫忙嗎?

請告訴我,如果需要一些更多的解釋。

下面是我的代碼:

接口:

package com.test.model; 

import org.springframework.beans.factory.annotation.Autowired; 

public interface AopInterface { 


    @Autowired 
    void addCustomerAround(String name); 
} 

類:

package com.test.model; 

import com.test.model.AopInterface; 
import org.springframework.stereotype.Component; 
import org.springframework.beans.factory.annotation.Autowired; 

@Component 
public class AopClass implements AopInterface { 

    public void addCustomerAround(String name){ 
     System.out.println("addCustomerAround() is running, args : " + name); 
    } 
} 

AOP:

package com.test.model; 

import java.util.Arrays; 

import org.aspectj.lang.ProceedingJoinPoint; 
import org.aspectj.lang.annotation.Around; 
import org.aspectj.lang.annotation.Aspect; 
import org.aspectj.lang.annotation.Pointcut; 



@Aspect 
public class TestAdvice{ 


    @Around("execution(* com.test.model.AopInterface.addCustomerAround(..))") 
     public void testAdvice(ProceedingJoinPoint joinPoint) throws Throwable { 

     System.out.println("testAdvice() is running!"); 


     } 
} 

appcontext:

<!-- Aspect --> 
    <aop:aspectj-autoproxy /> 
    <bean id="AopClass" class="com.test.model.AopClass" /> 
    <bean id="TestAdvice" class="com.test.model.TestAdvice" /> 

回答

2

只要把:

@Around("execution(* com.test.model..*.*(..))") 

執行表達式的格式是:

execution(modifiers-pattern? ret-type-pattern declaring-type-pattern? name-pattern(param-pattern) throws-pattern?) 

其中僅ret-type-pattern,需要name-patternparam-pattern,所以至少我們需要這樣一種表達:

execution(ret-type-pattern name-pattern(param-pattern)) 
  • ret-type-pattern任何
  • name-pattern返回類型,*比賽匹配方法名,你可以使用*作爲通配符和..指示子包
  • param-pattern比賽該方法的參數,爲(..)任意數量的參數

你可以在這裏找到更多的信息:10. Aspect Oriented Programming with Spring,有一些有用的examples