singleton | 以单例方式存在,每次返回同一个对象【也是spring的bean的默认作用域】 |
prototype | 返回一个新的实例,每次调用getBean() 相当于 new XXX; |
小编目前也是只了解这两个,其实还是有更多的,那么我们讲一下:
-
singleton:
Singleton是单例类型,就是在创建起容器时就同时自动创建了一个bean的对象,不管你是否使用,他都存在了,每次获取到的对象都是同一个对象。注意,singleton作用域是Spring中的缺省作用域。你可以在 bean 的配置文件中设置作用域的属性为 singleton,如下所示
-
prototype:
prototype是原型类型,它在我们创建容器的时候并没有实例化,而是当我们获取bean的时候才会去创建一个对象,而且我们每次获取到的对象都不是同一个对象。
我们分别看下设置不同的作用域调用ApplicationContext.getBean()方法 获取的对象是什么:
@Test
public void f() {
String xmlPath = "com/jishuai/testSrpingBean/bean.xml";
ApplicationContext applicationContext = new ClassPathXmlApplicationContext(xmlPath);
UserService userService1 = applicationContext.getBean("userServiceId1",UserServiceImpl.class);
UserService userService2 = applicationContext.getBean("userServiceId1",UserServiceImpl.class);
System.out.println("---------------实例化两个作用域为singlot的对象--------------");
System.out.println(userService1);
System.out.println(userService2);
System.out.println("---------------实例化两个作用域为prototype的对象---------------");
UserService userService3 = applicationContext.getBean("userServiceId2",UserServiceImpl.class);
UserService userService4 = applicationContext.getBean("userServiceId2",UserServiceImpl.class);
System.out.println(userService3);
System.out.println(userService4);
}
结果: