Is there an application-wide way of the defaulting the @Produces annotation on all JAX-RS /resources?
I have a lot of classes that produce web services. Rather than put @Produces({"application/json", "application/xml"})
on every one of them, I'd like to do it in a central place. That way I can add future producers in one place instead of having to modify every class.
I'm currently using Resteasy with Jetty.
The @Produces annotation is used to specify the MIME media types or representations a resource can produce and send back to the client. If @Produces is applied at the class level, all the methods in a resource can produce the specified MIME types by default.
The @Produces AnnotationIf applied at the method level, the annotation overrides any @Produces annotations applied at the class level. If no methods in a resource are able to produce the MIME type in a client request, the JAX-RS runtime sends back an HTTP “406 Not Acceptable” error.
@Consumes specifies what MIME type a resource accepts from the client. @Produces , however, specifies what MIME type a resources gives to the client. For example, a resource might accept application/json ( @Consumes ) and return text/plain ( @Produces ).
The annotation @Consumes is used to indicate the JAX-RS implementation how to dynamically parse/deserialize the body of your request in order to have it as parameter in a more convenient type. For example: @POST @Consumes("application/xml") public void registerUser(User user) { ... }
I know it's a bit old question but it could be helpful for someone else like me. As an addition to ccleve's solution you can use interfaces as well. Because of the multiple inheritance then you can combine multiple media types through interfaces. Example:
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public interface IJsonResource {
}
and
@Produces(MediaType.APPLICATION_XML)
@Consumes(MediaType.APPLICATION_XML)
public interface IXmlResource {
}
Then in your concrete JAX-RS resource class:
public class SomeJaxRsResource implements IJsonResource, IXmlResource {
...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With