Singleton spring bean不止一次被创建

时间:2014-04-27 01:11:45

标签: java spring spring-mvc web.xml

我有一个名为gameContext的单例spring bean,我的spring bean定义;

    <bean name="gameContext" scope="singleton"
      class="tr.com.hevi.game.numblock.core.context.GameContext"/>

我也使用这个类进行会话监听,这是我的web.xml

<listener>
    <listener-class>
        tr.com.hevi.game.numblock.core.context.GameContext
    </listener-class>
</listener>

问题是gameContext正在创建两次。一;在加载弹簧上下文之前的第一个,第二个;在春天的背景下。

我确信我不会多次进行分量扫描。

我理解背后的原因,但不知道如何解决这个问题。一种可能的解决方案应该是在spring上下文中添加监听器而不是web.xml,或者可能存在代理对象解决方案。

1 个答案:

答案 0 :(得分:3)

在您的问题中,spring有2个对象,因为您正在配置侦听器两次

  1. 第一个是在web.xml中(在spring上下文之外)
  2. 在春天的上下文中作为一个bean。
  3. 只有1个实例的最简单方法是使用Servlet 3.0规范。这里ServletContext有一个addListener()方法使用相同的方法。做类似下面的事情:

    @Component
    public class MyCustomListener implements javax.servlet.http.HttpSessionListener, ApplicationContextAware {
    
        @Override
        public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
            if (applicationContext instanceof WebApplicationContext) {
                ((WebApplicationContext) applicationContext).getServletContext().addListener(this);
            } else {
                //Either throw an exception or fail gracefully, up to you
                throw new RuntimeException("Must be inside a web application context");
            }
        }           
    }
    

    上述方法将导致您只创建一个侦听器对象,并将相同的对象注册为Servlet侦听器和spring bean。