Reputation: 4677
I have a ShapeService which I get from the application context. The shapeService is injected with a Circle and Triangle. I have getCircle() and getTriangle() in my shapeService. I also have an advice which is configured to get triggered whenever getter is called. The pointcut expression that is specified such that it is applicable for all the getters. So whenever getCircle() or getTriangle() gets called the advice gets triggered. But I was wondering why that is not getting triggered for applicationContext.getBean(). That is also a getter which satisfies the pointcut expression. Can anyone help me out figuring why it is not getting triggered.
@Aspect
@Component
public class LoggingAspect {
@Before("allGetters()")
public void loggingAdvice(JoinPoint joinPoint){
System.out.println(joinPoint.getTarget());
}
@Pointcut("execution(public * get*(..))")
public void allGetters(){}
}
This is the main class that gets the bean. Only the Shapeservice's getter and circle's getter is getting triggered and not the apllicationContext's 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());
}
}
Thanks
Upvotes: 0
Views: 619
Reputation: 1035
As implied by @Dave, to enable aspects you have to 'weave' them, either at compile time (CTW) or at class-loading time (LTW).
In order to benefit from the AspectJ+Spring magic, consider using e.g. LTW, which is quite flexible (you can weave aspects even to classes from 3rd-party jars without modifying them).
Start by reading the Spring Documentation, it's a good entry point. Basically:
<context:load-time-weaver/>
element in your Spring configCreate a META-INF/aop.xml
file in your classpath:
<!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>
java -javaagent:/path/to/lib/spring-instrument.jar foo.Main
Upvotes: 0
Reputation: 58094
The application context is not a Spring component (it is the container that manages other components), so if you are using Spring AOP it does not weave itself. If you used AspectJ you could intercept all getters, but even then only with load-time-weaving or if you recompile all jars on your classpath.
Upvotes: 1