通过spring注解开发,测试单例和多例区别
1.注解和配置两种用法形式
配置版:

注解版:

2.在spring框架中,scope作用域默认是单例的。
注:以下测试均是注解版
3.(1)多例:
配置类:
@Configuration
public class PersonConfigure {
//给容器中注册一个bean,类型为返回值的类型,id为方法名
@Scope("prototype") //多例
@Bean()
public Person person() {
System.out.println("bean被加载到容器中");
return new Person("张三",23);
}
}
单元测试:
@Test
public void test02() {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(PersonConfigure.class);
System.out.println("ioc容器加载完成");
Person bean = (Person) context.getBean("person");
bean.setName("lisi");
System.out.println(bean.toString());
Person bean1 = (Person) context.getBean("person");
System.out.println(bean1.toString());
System.out.println(bean==bean1);
}
}
测试结果:

结论:多例情况下,容器创建完成时不调用方法创建对象到容器中,在程序中获取时,才会将对象加载到容器中,而且每次调用生成的都是不同的对象。
(2)单例(注解版)
配置类:
//默认是单例
@Configuration
public class PersonConfigure {
//给容器中注册一个bean,类型为返回值的类型,id为方法名
@Bean()
public Person person() {
System.out.println("bean被加载到容器中");
return new Person("张三",23);
}
}
单元测试:
@Test
public void test02() {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(PersonConfigure.class);
System.out.println("ioc容器加载完成");
Person bean = (Person) context.getBean("person");
bean.setName("lisi");
System.out.println(bean.toString());
Person bean1 = (Person) context.getBean("person");
System.out.println(bean1.toString());
System.out.println(bean==bean1);
}
}
测试结果:

结论:单例情况下,容器创建时调用方法创建对象到容器中,在程序中调用bean,直接从容器中拿取,且每次拿取的都是同一个对象。如果上一次对bean里的属性做了修改,那下一次拿取的就是修改过的bean。
本文通过Spring注解开发,深入对比了单例和多例的区别。在Spring框架中,默认作用域为单例,而多例则需通过@Scope(prototype)指定。测试结果显示,多例情况下,容器不预先加载对象,每次获取都生成新实例;单例则在容器启动时创建对象,后续使用同一实例。
601

被折叠的 条评论
为什么被折叠?



