How to pool objects in Spring?

天涯浪子 提交于 2019-12-04 05:31:11

On each request, you create a brand new Spring application context, then you get new object in a new applicatin context each action. so you should load your spring context use 'ContextLoaderListener' in web.xml.

Reference fragment in web.xml

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>
        classpath*:spring/appContext.xml  classpath*:spring/appContext-security.xml
    </param-value>
</context-param>

<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

See you code:

try
{
    System.out.println("Accessing Application Context");
    ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
   ...

For more knowledge about Spring context loading, see MKyong 's tutorial or Spring reference

When you mention it means you are saying to service provider of urs pooling that you want to create maximum of two objects with object state provided via urs constructor.

  SimpleBean()
    {
        Random randomGenerator = new Random();
        randomNum = randomGenerator.nextInt(100);

        //I'm printing this line just to check if a instance of this bean is created.
        System.out.println("#####################A new SimpleBean was born: " + randomNum);

        str = "This is a string.";

    }

so SimpleBean simpleBean = (SimpleBean) context.getBean("simpleBean"); is a pooled object. iF two execution path want to get service from simpleBean then that object instance is provided via Pooling.If more thean two execution path then it is provided via prototype scope.

Try this will work...

<property name="targetSource" ref="poolTargetSource" />

<!-- Added so that different instance of object is created -->
<property name="singleton" value="false" />

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!