Where to place the @Produces and @Consumes annotation? In the method or class?

Asked

Viewed 241 times

1

I have been studying the operation of REST Apis in Java and came across two different didactics. In one of them the teacher placed the notes in the definition of the class, this way:

@Path("imoveis")
@Consumes(MediaType.APPLICATION_JSON + ";charset=utf-8")
@Produces(MediaType.APPLICATION_JSON + ";charset=utf-8")
public class .....

and in another teaching the teacher placed the notes specifically on top of each method, in this way:

@GET
@Consumes(MediaType.APPLICATION_JSON + ";charset=utf-8")
@Produces(MediaType.APPLICATION_JSON + ";charset=utf-8")
public ...... 

I would like to know the most correct way to declare these annotations, what are the advantages and disadvantages of each of them.

1 answer

2


In the example you showed, the two will end up resulting in the same configuration.

The difference in adoption should be exclusively related to your need.

  1. My controller will always consume and return JSON

In this case it makes no sense to put the annotations in each method (always remember the DRY!)

  1. My controller will consume and return multiple formats

In this situation, you can annotate the methods, because you will probably have specific methods consuming XML or other format, methods consuming only JSON, and methods consuming various formats.


Today you do not have a need to return or consume several/different formats, so it makes sense to leave only in the class. Tomorrow if you have XML as return and consumption (and the class is annotated), you can note only the method that will handle this situation with XML and the rest of the class will still handle JSON (as noted in the class).

In a practical way, the result is the same, you should consider the best structure of your code and avoid repetitions.

Complement:

As I pointed out in the commentary for better understanding, the idea would be to leave common things to most controllers in the class annotations, and then go on to specialize in the methods as needed (we should always consider DRY, leaving common things in only one place if possible)

  • In my case I had some methods that did not consume or return data, some methods that just returned, and also some that consumed and returned, so I was confused.

  • @Eduardo This is the same idea, usually settings that are most used by all methods tend to stay in class, and the methods specialize as needed

  • aa yes, now I understand.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.