简体   繁体   中英

Singleton bean instantiated multiple times in Spring MVC?

Does anyone know why this bean is getting instantiated multiple times? I only ever want one instance of it but every time the controller runs the construcutor is called again.

Here is the definition in my 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>

And in my controller here is where I'm using it - I though this would only get one instance of the DiameterClient class, but it is calling its constructor each time the code below runs - any help is much appreciated:

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

Note, DiameterClient is not my class, and I dont want to edit it, just want to have one global instance of it per application. Note also, DiameterClient extends Thread - not sure if this matters or not.

You are creating a new context each time and scope singleton means there is one instance in context. Usually you need one context per application execution. Move part below to a place executed once in your application:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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