Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JAX-RS default @Produces

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.

like image 949
ccleve Avatar asked Nov 24 '14 22:11

ccleve


People also ask

What is the @produces annotation used for?

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.

What is the use of @produce annotation of JAX-RS?

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.

What is the difference between @produces and @consumes?

@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 ).

What is the role of @consumes annotation in JAX-RS?

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) { ... }


1 Answers

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 {
...
}
like image 158
aberkes Avatar answered Sep 18 '22 20:09

aberkes