java - 为什么 Spring 会从 Singleton 类创建 2 个对象?

标签 java spring scope

我在这里可能是错的,但我无法弄清楚为什么 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>

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

最佳答案

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

原型(prototype)范围仅意味着:在调用 getBean 时返回一个新实例。

单例范围意味着:创建一个实例一次并始终返回该实例。

关于java - 为什么 Spring 会从 Singleton 类创建 2 个对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28255135/

相关文章:

java - 为什么要在 instanceOf 之后强制转换?

spring - 如何在集成测试阶段使用 Spring 嵌入式数据库初始化脚本?

spring - 在运行时未调用自定义 spring 安全过滤器

Javascript 变量提升在 Scratchpad 中的行为不符合预期

java - 当服务器名称包含反斜杠 (localhost\TESTDATA) 时使用 JDBC

java - 如何在 java 中创建自定义注释?

spring - xjc 绑定(bind)编译器配置将 xmlns 元素添加到 package-info 类?

function - 命名返回变量未在 for 循环中设置

android - Dagger 2 : Component cannot depend on multiple scoped components

java - 如何在Spring Controller 中从URL服务器inputStream