java - 如何在 Spring 中池化对象?

标签 java spring spring-3 spring-aop pooling

我正在关注这个 tutorial关于如何在 Spring 中池化对象。我已经按照教程中的说明进行操作,但是当我运行我的应用程序时,它总是会生成该对象的一个​​新实例。我期望因为我正在合并对象,所以现有对象将被重用。因此,不应创建新实例。此外,当我访问 bean 的 getter 方法时,将再次创建 bean 的新实例。

我可能做错了什么?我是否误解了 Spring 中池化的概念?

下面是我的代码:

应用上下文:(这只是我的应用上下文的主体。)

<bean id="simpleBeanTarget" class="com.bean.SimpleBean" scope="prototype">

</bean>

<bean id="poolTargetSource" class="org.springframework.aop.target.CommonsPoolTargetSource">
    <property name="targetBeanName" value="simpleBeanTarget" />
    <property name="maxSize" value="2" />
</bean>

<bean id="simpleBean" class="org.springframework.aop.framework.ProxyFactoryBean">
    <property name="targetSource" ref="poolTargetSource" />
</bean>

Controller :(这只是我方法的主体)

@RequestMapping("/hello")
public ModelAndView helloWorld(HttpServletRequest request, HttpServletResponse response)
{
    String message = "Hello World, Spring 3.";
    try
    {
        System.out.println("Accessing Application Context");
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");

        System.out.println("Getting Bean");
        SimpleBean simpleBean = (SimpleBean) context.getBean("simpleBean");
        //A new SimpleBean... is printed here.

        System.out.println("Displaying Hello World: " + simpleBean.getRandomNum());
        //After this line, A new SimpleBean... is printed again. I simply access the getter method. Why does it create a new instance of SimpleBean?

        return new ModelAndView("hello", "message", message);
    }catch(Exception e)
    {
        System.out.println("Error: " + e);
        e.printStackTrace();
        return new ModelAndView("hello", "message", "Error! " + e.getMessage());
    }
}

我正在汇集的 bean:

package com.bean;

import java.util.Random;

public class SimpleBean
{
    int randomNum;
    String str;

    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.";
    }

    public int getRandomNum()
    {
        return randomNum;
    }

    public void setRandomNum(int randomNum)
    {
        this.randomNum = randomNum;
    }

    public String getStr()
    {
        if (str == null)
            return "str is null";
        return str;
    }

    public void setStr(String str)
    {
        this.str = str;
    }
}

我的 web.xml 的主体:

<display-name>Spring3MVC</display-name>

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/classes/applicationContext.xml</param-value>
</context-param>

<welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
</welcome-file-list>

<servlet>
    <servlet-name>spring</servlet-name>
    <servlet-class>
        org.springframework.web.servlet.DispatcherServlet
    </servlet-class>
    <load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
    <servlet-name>spring</servlet-name>
    <url-pattern>*.html</url-pattern>
</servlet-mapping>

最佳答案

在每个请求中,您创建一个全新的 Spring 应用程序上下文,然后您在每个操作的新应用程序上下文中获取新对象。所以您应该在 web.xml 中使用“ContextLoaderListener”加载您的 spring 上下文。

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>

代码见:

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

有关 Spring 上下文加载的更多知识,请参阅 MKyong 's tutorialSpring reference

关于java - 如何在 Spring 中池化对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15472935/

相关文章:

Windows 上的 Java 进程使用的内存少于 -xms 中指定的内存?

java - Thymeleaf if 表达式不适用于主题参数值

java - NoHandlerFoundException 集中的 'parameters map' 在哪里?

java - 在另一个服务 Junit 中模拟一个服务的服务

java - 如何修复 NetBeans 生成的代码上的 'Exception in thread "AWT-EventQueue- 0"java.lang.NullPointerException'?

java - 为 XML 创建 MultipageEditor

java - 使用jboss5线程池启动线程

java - Spring MVC 中的 WebRequest 和 HttpServletRequest

maven-2 - 使用 CXF 和 Spring 构建 WS 需要哪些 maven2 工件?

spring-mvc - Spring 3 : @ResponseBody - How to control the response to get the XML or JSON?