spring中的Bean的作用域默認是單例的!
列如:<bean id="person" class="cm.xls.czq.spring.Person"></bean>
//加載xml配置文件
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("beans.xml");
//通過方法獲取對象
Person bean1 = (Person)applicationContext.getBean("person");
Person bean2 = (Person)applicationContext.getBean("person");
//打印
System.out.println(bean1 == bean2); //true
這就說明spring容器的bean默認是單列!
但是,我們也可以通過配置來改變bean的作用域!
<bean id="person" class="cm.xls.czq.spring.Person" scope="prototype"></bean>
//加載xml配置文件
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("beans.xml");
//通過方法獲取對象
Person bean1 = (Person)applicationContext.getBean("person");
Person bean2 = (Person)applicationContext.getBean("person");
//打印
System.out.println(bean1 == bean2); //false
這就說明每次都生成一個新的對象
總結:
scope="prototype" ---->每次都會產生一個新的實例
scope="singleton" ---->只能產生一個新的實例