Chapter 51. Annotation Inheritance
Abstract
JAX-RS annotations can be inherited by subclasses and classes implementing annotated interfaces. The inheritance mechanism allows for subclasses and implementation classes to override the annotations inherited from its parents.
Overview
Inheritance is one of the more powerful mechanisms in Java because it allows developers to create generic objects that can then be specialized to meet particular needs. JAX-RS keeps this power by allowing the annotations used in mapping classes to resources to be inherited from super classes.
JAX-RS's annotation inheritance also extends to support for interfaces. Implementation classes inherit the JAX-RS annotations used in the interface they implement.
The JAX-RS inheritance rules do provide a mechanism for overriding inherited annotations. However, it is not possible to completely remove JAX-RS annotations from a construct that inherits them from a super class or interface.
Inheritance rules
Resource classes inherit any JAX-RS annotations from the interface(s) it implements. Resource classes also inherit any JAX-RS annotations from any super classes they extend. Annotations inherited from a super class take precedence over annotations inherited from am interface.
In the code sample shown in Example 51.1, “Annotation inheritance”, the
Kaijin
class' getMonster()
method inherits the @Path
, @GET
, and @PathParam
annotations from the Kaiju
interface.
Example 51.1. Annotation inheritance
public interface Kaiju { @GET @Path("/{id}") public Monster getMonster(@PathParam("id") int id); ... } @Path("/kaijin") public class Kaijin implements Kaiju { public Monster getMonster(int id) { ... } ... }
Overriding inherited annotations
Overriding inherited annotations is as easy as providing new annotations. If the subclass, or implementation class, provides any of its own JAX-RS annotations for a method then all of the JAX-RS annotations for that method are ignored.
In the code sample shown in Example 51.2, “Overriding annotation inheritance”, the
Kaijin
class' getMonster()
method does not inherit any of the annotations from the Kaiju
interface. The implementation class overrides the @Produces
annotation which causes all of the annotations from the interface to be ignored.
Example 51.2. Overriding annotation inheritance
public interface Kaiju { @GET @Path("/{id}") @Produces("text/xml"); public Monster getMonster(@PathParam("id") int id); ... } @Path("/kaijin") public class Kaijin implements Kaiju { @GET @Path("/{id}") @Produces("application/octect-stream"); public Monster getMonster(@PathParam("id") int id) { ... } ... }