多个 bean 引用同一个 class?
Multiple bean referring to the same class?
在 Spring 配置文件中,我为同一个 class 创建了两个 bean,即
<bean id="emp1" class="Employee">
<property name="age" value="10"></property>
</bean>
<bean id="emp2" class="Employee">
<property name="age" value="15"></property>
</bean>
两者的范围默认为 'singleton' 但是当我打印 Employee 对象时,它显示了两个不同的对象。这怎么可能?我是说
如果 bean 范围是单例的,那么它是如何创建两个不同的对象的?
应该return2名员工。
Singleton 在 spring 中的含义略有不同——它不是保证每个 class 有 1 个实例。
这只是意味着每次你调用 "context.getBean("emp1")" 你都会得到相同的对象,而不是 "prototype" 这意味着每次调用 context.getBean("emp1")
试试这个
Object x1=context.getBean("emp1");
Object x2=context.getBean("emp1");
如果 "emp1" 是单例,您将获得相同的引用。如果是原型,您将获得两个单独的实例。
在 Spring 配置文件中,我为同一个 class 创建了两个 bean,即
<bean id="emp1" class="Employee">
<property name="age" value="10"></property>
</bean>
<bean id="emp2" class="Employee">
<property name="age" value="15"></property>
</bean>
两者的范围默认为 'singleton' 但是当我打印 Employee 对象时,它显示了两个不同的对象。这怎么可能?我是说 如果 bean 范围是单例的,那么它是如何创建两个不同的对象的?
应该return2名员工。 Singleton 在 spring 中的含义略有不同——它不是保证每个 class 有 1 个实例。 这只是意味着每次你调用 "context.getBean("emp1")" 你都会得到相同的对象,而不是 "prototype" 这意味着每次调用 context.getBean("emp1")
试试这个
Object x1=context.getBean("emp1");
Object x2=context.getBean("emp1");
如果 "emp1" 是单例,您将获得相同的引用。如果是原型,您将获得两个单独的实例。