有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java单例Springbean被创建了不止一次

我有一个名为gameContext的单例Springbean,这是我的Springbean定义

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

我也使用这个课程进行听力练习,这是我的网站。xml

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

问题是gameContext被创建了两次。一在加载spring上下文之前的最开始阶段,以及第二阶段;在spring上下文中

我确信我不会多次扫描组件

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


共 (1) 个答案

  1. # 1 楼答案

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

    1. 首先是网络。xml(在spring上下文之外)
    2. 在spring上下文中作为bean

    只有一个实例的最简单方法是使用Servlet3.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");
            }
        }           
    }
    

    上述方法将使您只创建侦听器的1个对象,并将同一对象注册为Servlet侦听器和Springbean