IOC操作Bean管理(bean作用域)
1、在Spring里面,设置创建bean示例是单实例还是多实例。
2、在Spring里面,默认情况下,bean是单实例对象。
示例如下:
Book.class:
package Module;
public class Book {
private int ID;
private String name;
public int getID() {
return ID;
}
public void setID(int ID) {
this.ID = ID;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
bean1.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="book" class="Module.Book"></bean>
</beans>
MainTest:
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import Module.Book;
public class MainTest
{
@Test
public void MainTest()
{
ApplicationContext context=new ClassPathXmlApplicationContext("bean1.xml");
Book book1=context.getBean("book",Book.class);
Book book2=context.getBean("book",Book.class);
System.out.println(book1);
System.out.println(book2);
}
}
由此可见book1与book2的地址是相同的,Spring里,默认的bean是单实例对象。
3、如何设置单实例或多实例:
(1)在spring配置文件bean标签里面有属性(scope)用于设置单实例还是多实例
(2)scope属性值
第一个值:默认值,singleton,表示单实例对象。
第二个值prototype,表示多实例对象。
设置多实例对象:
将bean1.xml里的scope属性设置为prototype:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="book" class="Module.Book" scope="prototype"></bean>
</beans>
测试结果:
可见,book1与book2的地址不相同
(3)singleton和prototype区别
第一:singleton单实例,prototype多实例
第二:设置scope值是singleton时候,加载spring配置文件时候就会创建单实例对象。
设置scope值是prototype时候,不是在加载spring配置文件时候创建对象,在调用getBean方法时候创建多实例对象。
另外scope还有两个值:request和session,
当scope值变为request时,每创建一个对象会放到request这个域对象中
当scope值变为session时,每创建一个对象会放到session中(web基础,session和request)