PNS
PNS

Reputation: 19895

Java REST web service constructor

Is there any point in having a constructor in a Java Web Service class? (There seems to be no consensus in the articles I have found so far.)

I am using Jersey to implement a REST web service that needs to have a non-static common object (a string-processing utility class) made available to various (non-static) methods of the service.

Initializing this common object would typically happen in the constructor of the class, if that were not a web service. But what about now that it is?

If a constructor cannot be used, should I put, in every relevant method, a synchronized block that checks whether the common object is available and, if not, initialize it? Or is there a better approach?

Upvotes: 4

Views: 6696

Answers (3)

Vivek Patwari
Vivek Patwari

Reputation: 29

Try @PostConstruct annotation. It might help you.

Upvotes: 1

soulcheck
soulcheck

Reputation: 36767

It's just an opinion, but if you want to adhere 100% to REST your web service should be stateless. Initializing common objects in web service method calls implies state so it's not the best idea.*

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

Contructor certainly is a solution, even better one would be to use dependency injection and inject the object you need to your webservice instance at creation.

Upvotes: 1

Perception
Perception

Reputation: 80593

Every web service class does have a constructor. If you don't include one then Java automatically adds the default no-arg constructor for you. You can:

  1. Initialize the utility instance when declaring it's class variable
  2. Manually add the default constructor and initialize the utility instance in it
  3. Or if your using JEE6 you can inject the utility instance into your web service

Upvotes: 3

Related Questions