Java REST Web Services Designer

Does it make sense to have a constructor in the Java Web Service class? (There is no consensus in the articles I have found so far.)

I use Jersey to implement a REST web service , which must have a non-static shared object (a utility class for processing strings), accessible for various (non-static) service methods.

Initialization of this shared object usually occurs in the constructor class if it is not a web service. But what now is it?

If the constructor cannot be used, should I put in each appropriate method a synchronized block that checks if the shared object is accessible, and if not, initialize it? Or is there a better approach?

+4
source share
3 answers

Each web service class has a constructor. If you do not enable it, then Java will automatically add the default no-arg constructor for you. You can:

  • Initialize a utility instance when declaring a class variable
  • Manually add a default constructor and initialize the utility instance in it
  • Or, if you use JEE6, you can enter an instance of the utility in your web service
+3
source

This is just an opinion, but if you want to adhere to a 100% REFUSAL, your web service should be stateless. Initializing shared objects in calls to a web service method implies state, so this is not a good idea. *

* This is debatable, as can be seen in the comments. However, any synchronization and shared object initialization, if IMO is not required, should be no-no in REST applications.

The contractor is definitely a solution, it would be even better to use dependency injection and inject the object you need into your webservice instance when you create it.

+1
source

Try the @PostConstruct annotation. It can help you.

+1
source

Source: https://habr.com/ru/post/1388598/


All Articles