How to create a single instance of object across entire Spring MVC web application?

Tags: , , , ,



I have a Spring MVC web application (XML based without annotations). I want to create only one instance of statsDClient object on start of my application and use it across my whole application. I am trying something like below:

import com.timgroup.statsd.NonBlockingStatsDClient;
import com.timgroup.statsd.StatsDClient;

Public class Helper(){

private static final StatsDClient statsDClient = new NonBlockingStatsDClient("prefix", "localhost", 8125);
private Helper(){}
 public static StatsDClient getInstance() {
      return statsDClient;
    }
}

Later in my controllers I am getting the statsDClient object in the following way:

public class HelpController extends AbstractController {
private StatsDClient statsDClient = Helper.getInstance();
protected ModelAndView handleRequestInternal(
            HttpServletRequest request,
            HttpServletResponse response) throws Exception {
statsDClient.someMethod();
}

But, this seems to be creating creating a new statsDClient object everything I use it in different controllers. Can you please guide where am I going wrong?

Answer

Beans in spring is by default singleton, which means only one shared instance is ever created and being managed by the spring container through out the entire application.

So in your case, you don’t need to specify statsDClient to be a single instance,

you could do something like to ensure statsDClient would have been instantiated once only but it’s just redundant

Pls refer to https://docs.spring.io/spring/docs/3.0.x/spring-framework-reference/htmlsingle/#beans-factory-scopes-singleton for better understanding



Source: stackoverflow