05 Bean的作用域

通过在<bean>标签中设置scope属性来指定作用域

  • singleton:默认的.容器初始时创建Bean实例.在整个容器的生命周期内只创建这一个Bean
  • prototype:容器初始化时不创建Bean实例.每次请求时创建一个新的实例

1. singleton

Address.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
package relation;/*
* @Author Sheng WenZeng
* @Date 2019/8/10 23:30
* @Version 1.0
*/

/**
* @author Sheng Wenzeng
* @ClassName Address
* @Description TODO
* @Date 2019/8/10 23:30
* @Version 1.0
*/
public class Address {
private String city;
private String street;

public Address() {
System.out.println("Address' construction...");
}

@Override
public String toString() {
return "Address{" +
"city='" + city + '\'' +
", street='" + street + '\'' +
'}';
}

public void setCity(String city) {
this.city = city;
}

public void setStreet(String street) {
this.street = street;
}
}

Main.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
package relation;/*
* @Author Sheng WenZeng
* @Date 2019/8/10 23:31
* @Version 1.0
*/

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
* @author Sheng Wenzeng
* @ClassName Main
* @Description TODO
* @Date 2019/8/10 23:31
* @Version 1.0
*/
public class Main {
public static void main(String[] args) {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
Address address = (Address) applicationContext.getBean("address");
Address address_1 = (Address) applicationContext.getBean("address");
System.out.println(address == address_1);
}
}

applicationContext.xml

1
2
3
4
5
6
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean scope="singleton" id="address" class="relation.Address" p:city="Beijing" p:street="NanJingLu"/>
</beans>

输出结果为:

1
2
Address' construction...
true

可见只是在容器初始化时创建了一次Bean,而后获取的Bean都是同一个对象

2. prototype

将上面的xml文件修改如下:

1
2
3
4
5
6
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean scope="prototype" id="address" class="relation.Address" p:city="Beijing" p:street="NanJingLu"/>
</beans>

而后运行,结果为:

1
2
3
Address' construction...
Address' construction...
false

可见容器初始化时没有新建Bean对象,而是每次请求时创建一个新的Bean对象

评论

Your browser is out-of-date!

Update your browser to view this website correctly.&npsb;Update my browser now

×