2012-11-27 25 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> 
  • 运行