當我們在spring容器中添加一個bean時,如果沒有指明它的scope屬性,則默認是singleton,也就是單例的。
例如先聲明一個bean:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
public class People { private String name; private String sex; public String getName() { return name; } public void setName(String name) { this .name = name; } public String getSex() { return sex; } public void setSex(String sex) { this .sex = sex; } } |
在applicationContext.xml文件中配置
1
2
3
4
5
6
7
8
9
10
|
<?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-4.1.xsd" > <bean id= "people" class = "People" ></bean> </beans> |
然后通過spring容器來獲取它:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class SpringTest { public static void main(String[] args) { ApplicationContext context= new ClassPathXmlApplicationContext( "applicationContext.xml" ); People p1=(People) context.getBean( "people" ); People p2=(People) context.getBean( "people" ); System.out.println(p1); System.out.println(p2); } } |
運行之后可以看出p1和p2輸入的內容是一樣的,說明spring中的bean是單例的。
如果不想要單例的bean,可以將scope的屬性改為prototype
1
|
<bean id= "people" class = "People" scope= "prototype" ></bean> |
這樣通過spring容器獲取的bean就不是單例的了。
spring容器默認情況下在啟動之后就自動為所有bean創建對象,若想要在我們獲取bean時才創建的話,可以使用lazy-init屬性
該屬性有三個值defalut,true,false。默認是default,該值和false一樣,都是spring容器啟動時就創建bean對象,當指定為true時,
在我們獲取bean時才創建對象。
以上這篇淺談spring容器中bean的初始化就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持服務器之家。