Java Annotation Processors and Spring @Transactional Rollback Pitfalls
This article explains how Java annotation processors work, why @Transactional requires rollbackFor=Exception.class to roll back checked exceptions, and provides a complete example of a custom processor using auto-service to enforce this Spring transaction configuration.
Java annotation processors are part of the Java compiler and can scan annotations at compile time to generate code, perform checks, or produce documentation.
When using Spring's @Transactional, only unchecked exceptions trigger rollback by default; checked exceptions such as java.lang.Exception do not, so the annotation must be configured with @Transactional(rollbackFor = Exception.class) to ensure rollback.
The article explains that an annotation must have a runtime retention policy ( RetentionPolicy.RUNTIME ) to be visible to an annotation processor, which is why @Transactional can be processed.
To implement a custom processor, one extends javax.annotation.processing.AbstractProcessor and registers the implementation via the SPI file META-INF/services/javax.annotation.processing.Processor . The auto-service library can generate this file automatically.
Example Maven dependency for auto-service is shown, followed by a complete processor implementation that scans for @Transactional, extracts the rollbackFor attribute, and throws a runtime exception if the required configuration is missing.
After building the processor JAR and adding it as a Maven dependency, the article demonstrates compilation errors that occur when the configuration is absent, reinforcing the need to set rollbackFor = Exception.class .
In summary, Java annotation processors enable compile‑time code generation and validation, and can be used to enforce Spring transaction settings, with tools like Lombok, auto-service, and error‑prone providing common use cases.
Cognitive Technology Team
Cognitive Technology Team regularly delivers the latest IT news, original content, programming tutorials and experience sharing, with daily perks awaiting you.
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.