简体   繁体   English

如何在整个 Spring MVC web 应用程序中创建 object 的单个实例?

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

I have a Spring MVC web application (XML based without annotations).我有一个 Spring MVC web 应用程序(基于 XML 没有注释)。 I want to create only one instance of statsDClient object on start of my application and use it across my whole application.我只想在我的应用程序启动时创建一个statsDClient object 实例,并在整个应用程序中使用它。 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:稍后在我的控制器中,我通过以下方式获取statsDClient object:

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.但是,这似乎是在创建一个新的statsDClient object 我在不同控制器中使用的所有内容。 Can you please guide where am I going wrong?你能指导我哪里出错了吗?

Variables that marked static was created only once in memory.标记为 static 的变量仅在 memory 中创建一次。 You can create a bean and inject it wherever you need.您可以创建一个 bean 并将其注入到您需要的任何位置。

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. spring 中的 Bean 默认为 singleton,这意味着在整个应用程序中只创建一个共享实例并由 spring 容器管理。

So in your case, you don't need to specify statsDClient to be a single instance,因此,在您的情况下,您无需将 statsDClient 指定为单个实例,

you could do something like to ensure statsDClient would have been instantiated once only but it's just redundant你可以做一些事情来确保 statsDClient 只会被实例化一次,但这只是多余的

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM