2012-11-27 53 views
0

我有一個從應用程序上下文獲得的ShapeService。 shapeService注入了一個Circle和Triangle。我的shapeService中有getCircle()和getTriangle()。我也有一個建議,配置爲每當調用getter時觸發。指定的切入點表達式使其適用於所有獲取者。所以每當getCircle()或getTriangle()被調用時,都會觸發建議。但我想知道爲什麼沒有爲applicationContext.getBean()觸發。這也是一個滿足切入點表達式的getter。任何人都可以幫我找出爲什麼它沒有被觸發。getBean()沒有被觸發的AOP通配符

@Aspect 
@Component 
    public class LoggingAspect { 

    @Before("allGetters()") 
    public void loggingAdvice(JoinPoint joinPoint){ 
     System.out.println(joinPoint.getTarget()); 
    } 

    @Pointcut("execution(public * get*(..))") 
    public void allGetters(){} 
} 

這是獲取bean的主要類。只有Shapeservice的getter和圓形的吸氣劑得到觸發,而不是apllicationContext的的getBean

public class AopMain { 
     public static void main(String[] args) { 
     ApplicationContext ctx = new ClassPathXmlApplicationContext("spring-config.xml"); 
     ShapeService shapeService = ctx.getBean("shapeService", ShapeService.class); 
     System.out.println(shapeService.getCircle().getName()); 

    } 
} 

感謝

回答

1

應用程序上下文是不是一個Spring組件(它是管理其他組件的容器),所以如果你是使用Spring AOP它不會自己編織。如果你使用了AspectJ,你可以攔截所有的getter,但即使這樣也只有加載時編織或者你重新編譯你的類路徑上的所有jar。

0

正如@Dave所暗示的那樣,爲了能夠在編譯時(CTW)或上課時間(LTW)「編織」它們。

爲了受益於AspectJ + Spring的魔法,請考慮使用例如LTW,這是非常靈活的(你可以編織方面,甚至從第三方罐子類沒有修改它們)。

首先閱讀the Spring Documentation,這是一個很好的切入點。 基本上是:

  • 將一個<context:load-time-weaver/>元素在你的Spring配置
  • 創建META-INF/aop.xml文件在類路徑:java -javaagent:/path/to/lib/spring-instrument.jar foo.Main

與編織Java代理
<!DOCTYPE aspectj PUBLIC "-//AspectJ//DTD//EN" "http://www.eclipse.org/aspectj/dtd/aspectj.dtd"> 
<aspectj> 
    <weaver> 
    <!-- include your application-specific packages/classes --> 
    <!-- Nota: you HAVE TO include your aspect class(es) too! --> 
    <include within="foo.ShapeService"/> 
    <include within="foo.LoggingAspect"/> 
    </weaver> 
    <aspects> 
    <!-- weave in your aspect(s) -->   
    <aspect name="foo.LoggingAspect"/> 
    </aspects> 
</aspectj> 
  • 運行