目錄:html
瞭解Spring的基本概念spring
Spring簡單的示例session
簡單地說Bean是被Spring容器管理的Java對象,Spring容器會自動完成對Bean的實例化。app
那麼什麼是容器呢?若是看過上篇簡單的Spring示例。
post
其中有以下代碼:學習
ApplicationContext context=new ClassPathXmlApplicationContext("applicationContext.xml");
context就是一個容器,固然這不是官方最準確的定義,不過初步學習,咱們知道這個實例化對象就是個容器就好了。測試
第二篇隨筆中,配置文件內容以下:this
<?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-3.0.xsd"> <!-- id本身命名,class就是須要注入屬性的類--> <bean id="c" class="Category"> <!-- name就是屬性的名稱,value就是注入到該屬性的值--> <property name="name" value="Hello Word"/> </bean> </beans>
bean定義時的屬性列表以下(摘自w3cschool):url
屬性 | 描述 |
---|---|
class | 這個屬性是強制性的,而且指定用來建立 bean 的 bean 類。 |
name | 這個屬性指定惟一的 bean 標識符。在基於 XML 的配置元數據中,你可使用 ID 和/或 name 屬性來指定 bean 標識符。 |
scope | 這個屬性指定由特定的 bean 定義建立的對象的做用域,它將會在 bean 做用域的章節中進行討論。 |
constructor-arg | 它是用來注入依賴關係的,並會在接下來的章節中進行討論。 |
properties | 它是用來注入依賴關係的,並會在接下來的章節中進行討論。 |
autowiring mode | 它是用來注入依賴關係的,並會在接下來的章節中進行討論。 |
lazy-initialization mode | 延遲初始化的 bean 告訴 IoC 容器在它第一次被請求時,而不是在啓動時去建立一個 bean 實例。 |
initialization 方法 | 在 bean 的全部必需的屬性被容器設置以後,調用回調方法。它將會在 bean 的生命週期章節中進行討論。 |
destruction 方法 | 當包含該 bean 的容器被銷燬時,使用回調方法。它將會在 bean 的生命週期章節中進行討論。 |
上面表格中,scope屬性就是用來指定做用域的。其值及描述以下:spa
做用域 | 描述 |
---|---|
singleton | 在spring IoC容器僅存在一個Bean實例,Bean以單例方式存在,默認值 |
prototype | 每次從容器中調用Bean時,都返回一個新的實例,即每次調用getBean()時,至關於執行newXxxBean() |
request | 每次HTTP請求都會建立一個新的Bean,該做用域僅適用於WebApplicationContext環境 |
session | 同一個HTTP Session共享一個Bean,不一樣Session使用不一樣的Bean,僅適用於WebApplicationContext環境 |
global-session | 通常用於Portlet應用環境,該運用域僅適用於WebApplicationContext環境 |
下面咱們就來寫兩個經常使用的做用域。
首先準備一個類,這個類不用變
public class Category { //屬性 private String name; //設置該屬性的方法 public void setName(String name){ this.name=name; } //獲取該屬性的方法 public void getName(){ System.out.println(name); } }
singleton做用域:
配置文件:
<?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-3.0.xsd"> <!-- id本身命名,class就是須要注入屬性的類--> <bean id="c" class="Category" scope="singleton"> </bean> </beans>
測試類
public class TestSpring { public static void main(String[] args) { //Spring的API ApplicationContext。applicationContext.xml就是本身建立的配置文件 ApplicationContext context=new ClassPathXmlApplicationContext("applicationContext.xml"); //c就是後面配置文件的id Category category=(Category)context.getBean("c"); //不在配置文件中設置,用set方法設置屬性的值 category.setName("第一次設置"); category.getName(); //第二個對象 Category category1=(Category)context.getBean("c"); //不用設置,直接獲取屬性的值 category1.getName(); } }
最後的結果是:
第一次設置
第一次設置
兩次輸出相同的內容,說明id爲c的bean只有1個,兩次返回的都是同一個值。
prototype做用域:
配置文件中的scope改爲prototype。其餘全部代碼不變,包括測試類
最後輸出:
第一次設置
null
說明容器每次調用getBean時返回的是一個新的實例,因此第一次設置對第二個對象無效。