I have the following Spring Boot class, annotated with the custom annotation Counted
:
@RestController
@RequestMapping("/identity")
public class IdentityController {
@Autowired
private IdentityService identityService;
@PostMapping
@Counted(value = "post_requests_identity")
public Integer createIdentity() {
return identityService.createIdentity();
}
}
The Counted
annotation is defined as follows:
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.SOURCE)
public @interface Counted {
String value();
}
What I want is to write an annotation processor that effectively makes my Controller behave like the below code.
@RestController
@RequestMapping("/identity")
public class IdentityController {
@Autowired
private IdentityService identityService;
@Autowired
private PrometheusMeterRegistry registry;
@PostConstruct
public void init() {
registry.counter("post_requests_identity");
}
@PostMapping
public Integer createIdentity() {
registry.counter("post_requests_identity").increment();
return identityService.createIdentity();
}
}
I have been able to do this with reflection at runtime, but that greatly extends startup time. Is there a way to do the above with just annotations and a custom annotation processor? Put into words, I want to create an annotation that adds an annotated method to a class, and adds an arbitrary method call to an already existing method.
I am aware that annotation processing does not really support modifying the source. I'd be interested in knowing any other method for me to do the above without putting the registry and its associated code directly in my source code.