Jyotirup Jyotirup - 1 year ago 96
Java Question

Should a Service class be singleton in java?

While designing a service class should it be singleton in java? Generally DAO is made singleton, so should the calling Service class be made singleton also?

Answer Source

Singletons are bad, if you develop them. If you are using dependency injection, let the DI container handle the singleton nature of your Service object. If you are not using dependency injection, use a static method instead of a singleton.

Classic example of bad:

public class HootUtility // singleton because developer was a goofball.
   public void blammy(...) { ... }
   public HootUtility getInstance() { ... }

... somewhere in the code.

HootUtility.getInstance().blammy(...);  // This is silly.

Better implementation of the above:

public class HootUtility // Not a singleton because I am not a ______. (fill in the blank as you see fit)
  // You can limit instantiation but never prevent instantiation.
  // google "java reflection" for details.
  private HootUtility()
    throw new UnsuppotedOperationException();

  public static void blammy(...) { ... }

... somewhere in the code.


If you have a service interface that has an concrete implementation, use a dependency injection framework to inject the implementation (DI frameworks include: spring and guice).

Edit: If I was using spring, I would choose singleton scope (the default).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download