【问题标题】:Singleton bean instantiated multiple times in Spring MVC?在 Spring MVC 中多次实例化单例 bean?
【发布时间】:2012-02-09 13:14:07
【问题描述】:

有谁知道为什么这个 bean 会被多次实例化?我只想要它的一个实例,但每次控制器运行时都会再次调用构造函数。

这是我的 applicationContext.xml 中的定义

<bean id="DiameterClient" class="com.rory.diameter.client.DiameterClient" scope="singleton" init-method="start">
    <constructor-arg type="java.lang.String" index="0"><value>${pcca.host}</value></constructor-arg>      
    <constructor-arg index="1"><value>${pcca.port}</value></constructor-arg>      
    <constructor-arg index="2" value="com.openwave.djgx.message"/>
    <constructor-arg index="3" value="com.openwave.djgx.avp"/>    
</bean>

在我的控制器中,这是我使用它的地方 - 虽然这只会获得 DiameterClient 类的一个实例,但每次运行下面的代码时它都会调用它的构造函数 - 非常感谢任何帮助:

BeanFactory factory = new ClassPathXmlApplicationContext("applicationContext.xml");
DiameterClient diameterClient = (DiameterClient)factory.getBean("DiameterClient");
diameterClient.send(aar);

注意,DiameterClient 不是我的课程,我不想编辑它,只想为每个应用程序提供一个全局实例。另请注意,DiameterClient 扩展了 Thread - 不确定这是否重要。

【问题讨论】:

    标签: java spring spring-mvc singleton web.xml


    【解决方案1】:

    您每次都在创建一个新的上下文,范围 singleton 表示上下文中有一个实例。通常每个应用程序执行都需要一个上下文。将下面的部分移动到您的应用程序中执行一次的位置:

    BeanFactory factory = new ClassPathXmlApplicationContext("applicationContext.xml");
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-11-30
      • 2017-04-23
      • 2016-06-08
      • 1970-01-01
      • 1970-01-01
      • 2016-07-11
      • 2012-08-30
      相关资源
      最近更新 更多