Registering Annotation Processors
You'll learn how to make the Java compiler discover and execute your custom annotation processors during compilation.
The Registration Challenge
You've built an annotation processor by extending AbstractProcessor, but how does the compiler know it exists? Unlike runtime reflection where you explicitly invoke code, compile-time processors must be registered so javac can automatically discover and load them. Think of it like signing up for a service—you need to put your name on a list somewhere official.
Two Registration Approaches
1. Manual Registration with META-INF/services
The traditional approach uses the Java Service Provider Interface (SPI). Create a text file at this exact path in your JAR:
META-INF/services/javax.annotation.processing.Processor
Inside this file, list the fully qualified names of your processor classes, one per line:
com.example.MyProcessor
com.example.AnotherProcessor
When javac runs, it scans this file in all JARs on the annotation processor path and loads your processors automatically.
2. The @AutoService Pattern
Google's AutoService library eliminates manual file creation. Simply annotate your processor:
@AutoService(Processor.class)
public class MyProcessor extends AbstractProcessor {
// your implementation
}
During compilation, AutoService itself generates the META-INF/services file for you. It's a processor that helps register processors—meta indeed! This prevents typos and keeps everything in sync.
Practical Notes
Both approaches achieve the same result: making your processor discoverable. The META-INF/services file is part of the JAR specification, so it works everywhere. @AutoService is a convenience wrapper that reduces boilerplate and human error.
Key Takeaway: Register annotation processors either by manually creating a META-INF/services/javax.annotation.processing.Processor file listing your processor classes, or use @AutoService(Processor.class) to generate this registration automatically.