The goal is to develop an annotation that marks certain functions to execute predefined logic via an Interceptor such as adding a correlationId to the MDC. I also want to place the code in a shared library so it can be used across multiple services.
Create the annotation and the interceptor
A simple annotation:
@InterceptorBinding
@Target({METHOD, TYPE})
@Retention(RUNTIME)
public @interface AddCorrelationId {
}
Basic interceptor:
@Interceptor
@Priority(Interceptor.Priority.APPLICATION)
@AddCorrelationId
public class AddCorrelationIdInterceptor {
@AroundInvoke
Object intercept(InvocationContext ctx) throws Exception {
try {
MDC.put(CORRELATION_ID_MDC_KEY, UUID.randomUUID().toString());
return ctx.proceed();
} finally {
MDC.clear();
} }}
The code above is just plain Java and it is sufficient when the code lives within the service. However, if instead the code lives in a shared library in Quarkus, something extra becomes necessary.
Make it discoverable by Quarkus
Add META-INF/beans.xml
<beans xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/beans_1_1.xsd"
bean-discovery-mode="all">
</beans>
Add META-INF/quarkus-extension.yaml. This file is used to define a custom Quarkus extension: it provides metadata about the extension so Quarkus tooling and build processes can recognise it.
name: My Quarkus Commons
description: A collection of shared functions
deployment-artifact: com.alros:my-quarkus-commons