作用域类型
在Spring中,可以在元素的属性中设置bean的作用域,以决定这个bean是单例的还是多实例的
默认情况下,Spring只为每个在IOC容器里生命的bean创建唯一一个实例,整个IOC容器范围内都能共享该实例:所有后续的getBean()调用和bean引用都将返回这个唯一bean实例。该作用于被称为singleton,它是所有bean的默认作用域
类别 | 说明 |
---|---|
singleton | 在SpringIOC容器中仅存在一个Bean实例,Bean以单实例的方式存在 |
prototype | 每次调用getBean()时都会返回一个新的实例 |
request | 每次HTTP请求都会创建一个新的Bean,该作用域仅适合于WebApplicationContext环境 |
session | 同一个HTTP Session 共享一个Bean,不同的HTTP session使用不同的Bean。该作用域仅适合于WebApplicationContext环境 |
当bean的作用域为单例时,Spring会在IOC容器对象创建时就创建bean的对象实例
代码测试
public class Book {
private Integer id;
private String title;
private String author;
private double price;
private Integer sales;
public Book() {
System.out.println("Book对象被创建了");
}
public Book(Integer id, String title, String author, double price, Integer sales) {
super();
this.id = id;
this.title = title;
this.author = author;
this.price = price;
this.sales = sales;
System.out.println("全参的构造器被调用");
}
public Book(Integer id, String title, String author, double price) {
super();
this.id = id;
this.title = title;
this.author = author;
this.price = price;
System.out.println("不含销量的构造器被调用");
}
public Book(Integer id, String title, String author, Integer sales) {
super();
this.id = id;
this.title = title;
this.author = author;
this.sales = sales;
System.out.println("不含价格的构造器被调用");
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public Integer getSales() {
return sales;
}
public void setSales(Integer sales) {
this.sales = sales;
}
@Override
public String toString() {
return "Book [id=" + id + ", title=" + title + ", author=" + author + ", price=" + price + ", sales=" + sales
+ "]";
}
}
class SpringTest {
//01.Spring Bean的作用域之间有什么区别
//创建IOC容器对象
ApplicationContext ioc = new ClassPathXmlApplicationContext("beans.xml");
@Test
void testBook() {
Book book = (Book) ioc.getBean("book");
Book book2 = (Book) ioc.getBean("book");
System.out.println(book==book2);
}
}
更改beans.xml中的配置
<bean id="book" class="com.atguigu.spring.beans.Book" scope="singleton">
<property name="id" value="8"></property>
<property name="title" value="红高粱"></property>
<property name="author" value="莫言"></property>
<property name="price" value="10.00"></property>
<property name="sales" value="800"></property>
</bean>
- singleton 时 ,运行结果如下: 只创建一次bean
- prototype:运行结构如下
<bean id="book" class="com.atguigu.spring.beans.Book" scope="prototype">
...
</bean>
每次实例化都会创建一个新的Book对象
学习途径:尚硅谷视频