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" ---->只能产生一个新的实例