Injecting Jar Version into Java Components Using a Compile‑Time Annotation Processor
This article explains how to create a custom compile‑time annotation processor that automatically injects the current JAR version into Java component constants, eliminating manual updates and enabling Prometheus monitoring of version usage across internal libraries.
The author describes a practical need: a company maintains a set of reusable Java backend components (e.g., circuit‑breaker, load‑balancer, RPC) packaged as JARs, and wants to monitor which versions are used via Prometheus. Manually updating a version constant in each component is error‑prone.
To solve this, a custom compile‑time (insertion) annotation processor is introduced, similar to Lombok’s approach. By defining an annotation @TrisceliVersion and a processor that runs during the Java compilation phase, the processor reads the current project version and injects it into a static final String version field.
@Documented @Retention(RetentionPolicy.SOURCE) @Target({ElementType.FIELD}) public @interface TrisceliVersion {}
The processor extends AbstractProcessor and overrides process() to locate fields annotated with @TrisceliVersion , verify they are of type String , and replace their initializer with a literal containing the version (e.g., "v1.0.1" ). It uses internal compiler APIs ( JavacTrees , TreeMaker ) to modify the abstract syntax tree (AST) before bytecode generation.
Registration of the processor is done via the SPI mechanism by creating a META-INF/services/javax.annotation.processing.Processor file that lists the processor class name.
After building the project with Gradle, the generated bytecode contains the injected version value, which can then be exposed to Prometheus for monitoring. The article includes screenshots of the test module, the generated class, and the monitoring result.
Finally, the author notes that insertion‑type annotation processors can enable many powerful compile‑time code generation scenarios beyond version injection, similar to Lombok’s getter/setter generation.
Architecture Digest
Focusing on Java backend development, covering application architecture from top-tier internet companies (high availability, high performance, high stability), big data, machine learning, Java architecture, and other popular fields.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.