Use case
I'd like to add programmatically an externally provided annotation named: @Trace
- to all public methods in the spring-boot project
- that are in a class annotated with
@Controller - only within a particular package (
com.example.apectitddemo.controller) - only if the method doesn't have a different custom annotation already applied, f.e.
@Disable
Thanks to the above criteria, each newly added method to the project that meets them all will be @Trace annotated dynamically without any additional developer action, which is the main goal here.
My approach
I used Aspectj's ITD (inter type declaration) for this but it fulfills only 1st requirement and have no idea how to customize it for 2nd, 3rd and 4th. Tried several ways commented out in the below code snipped.
TracingAspect.aj:
package com.example.apectitddemo.aspect;
public aspect TracingAspect {
declare @method : public * *(..) : @Trace;
//[INFO] 'public void com.example.apectitddemo.controller.ControllerPing.ping()' (ControllerPing.java) is annotated with @Trace method annotation from 'com.example.apectitddemo.aspect.TracingAspect' (TracingAspect.aj)
// declare @method : public * ((@Controller *)).*(..) : @Trace;
// declare @method : public * ((@Controller *)).*(..) && !@Disabled : @Trace;
// declare @method : public com.example.apectitddemo.controller.* :@Trace;
// declare @method : public * com.example.apectitddemo.controller+ : @Trace;
// declare @method : public * *(com.example.apectitddemo.controller.*) : @Trace;
// declare @method : public * controller..* : @Trace;
// declare @method : public * *(..) : @Trace;
}
BTW is it possible to use pure java here (TracingAspect.java) and not as .aj file?
ControllerPing.java (sample method which should be annotated by an aspect)
package com.example.apectitddemo.controller
@Controller
public class ControllerPing {
//@Trace annotation should be added here by ITD
public void ping() {
log.info("ok");
}
@Disable
public void pingDisabled() {
log.info("ok");
}
}
Misc
I was searching the internet but haven't found much documentation and even couldn't encounter any other code samples except below. The above solution is based on this finding:
Other pages found, related:
- https://www.eclipse.org/aspectj/doc/released/adk15notebook/ataspectj-itds.html
- http://kto.web.elte.hu/hu/oktatas/aop_en.pdf
- samples are empty :/ https://www.eclipse.org/aspectj/doc/released/examples/
Maybe there is another better way to complete the requirements?