如何检查使用scope = prototype创建的对象是否为新对象而不是旧对象

时间:2016-02-24 18:09:08

标签: spring scope prototype

在Spring中,我们有作为单例和原型的范围。 Scope = prototype每次获取Bean()时都会创建新对象。 我的问题是,我们如何验证它是否真的是新对象而不是现有对象?

1 个答案:

答案 0 :(得分:1)

这是一个快速演示。 Bean A是原型bean,Bean B不是。每个类都实现InitializingBean,以允许在创建新对象时进行打印。然后将要求容器创建两次bean,并且将比较对象的相等性:

Bean A定义;和Bean B完全一样:

@Component
public class A implements InitializingBean {

    // ... properties, etc

    @Override
    public void afterPropertiesSet() throws Exception {
        System.out.println("Creating A");
    }

}

配置类:

@Configuration
@ComponentScan(basePackages = "com.test.config")
public class AppConfig {

    @Bean
    @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
    public A a() {
        A a = new A();
        return a;
    }

    @Bean
    public B b() {
        B b = new B();
        return b;
    }
}

然后在每个bean上使用两次getBean()来测试相等性:

 A a = (A)ctx.getBean("a"); 
 B b = (B)ctx.getBean("b"); 
 A a2 = (A)ctx.getBean("a");
 B b2 = (B)ctx.getBean("b"); 

 System.out.println("A is a " + (a == a2 ? "Singleton" : "Prototype"));
 System.out.println("B is a " + (b == b2 ? "Singleton" : "Prototype"));

你得到了预期的结果,表明A每次调用getBean()时都会创建一个新的Object,而B则不会。

Creating A
Creating A
A is a Prototype
B is a Singleton