【问题标题】:Why would Spring create 2 objects from Singleton class?为什么 Spring 会从 Singleton 类创建 2 个对象?
【发布时间】:2015-01-31 18:39:03
【问题描述】:

我在这里可能错了,但我无法弄清楚为什么 Spring 从 Singleton 类创建 2 个不同的对象。以下是代码:

public class DbSingleTOn {

    private static DbSingleTOn dbSingleTOn = new DbSingleTOn();
    private DbSingleTOn() {
    }
    public static DbSingleTOn getInstance() {
        return dbSingleTOn;
    }
}

public class MyApp {

    public static void main(String[] args) {
        AbstractApplicationContext context = new ClassPathXmlApplicationContext(
                "spring-singleton.xml");
        DbSingleTOn dbSingleTOn = context.getBean(DbSingleTOn.class);
        System.out.println(dbSingleTOn.hashCode());

        DbSingleTOn dbSingleTOn1 = context.getBean(DbSingleTOn.class);
        System.out.println(dbSingleTOn1.hashCode());

        context.registerShutdownHook();
    }
}

Output:
18885489
17045421

Spring 配置 XML:

<bean id="bean1" class="com.singleton.DbSingleTOn" scope="prototype" >
    </bean>

预期使用“原型”作用域为普通类获取不同的对象,但是,为什么“原型”会从 Singleton 类创建 2 个对象?

【问题讨论】:

    标签: java spring scope


    【解决方案1】:

    仅仅因为您在静态字段中创建了一个单例,这不会对 spring 产生影响。 Spring 根本没有意识到这一点。

    原型作用域仅仅意味着:当getBean被调用时返回一个新的实例。

    单例作用域意味着:创建一次实例并始终返回该实例。

    【讨论】:

      【解决方案2】:

      两件事。一,Spring 不知道(而且真的不在乎)你的类是如何设置的。您已经实现了编程模式这一事实对 Spring 没有任何意义。第二,Spring 使用反射来实例化您声明的 bean 类型,因此可以使用您的 private 构造函数。

      每次你从 Spring 请求一个原型作用域的 bean 时,它都会创建一个新的 bean 实例。

      【讨论】:

      • @Scotirios 我有一种预感,Spring 必须通过反射加载类,因此是预期的行为。感谢您的确认。
      【解决方案3】:

      如果你不直接设置如何实例化 bean,Spring 使用反射来调用构造函数来创建 bean。除了使用默认的单例范围之外,您还可以在您的 xml 配置中将 factory-method 设置为 getInstance 以告诉 Spring 如何创建您的 bean。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-01-15
        • 2013-07-04
        • 2012-08-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多