1. 程式人生 > >【Java Web】Spring中Bean的使用

【Java Web】Spring中Bean的使用

Bean的定義

被稱作 bean 的物件是構成應用程式的支柱,其也由 Spring IoC 容器管理的。bean 是一個被例項化、組裝、並通過 Spring IoC 容器所管理的物件。這些 bean 是由用容器提供的配置元資料建立的,例如,已經在先前章節看到的,在 XML 的表單中的 定義。

定義Bean

1540112787436

建立一個Bean類Student(要包含get、set、空構造方法),再建立一個SpringConfig檔案,新增如上圖的程式碼。其中標籤中id屬性是唯一性識別符號,class屬性是指定bean例項化時用到的類,scope是用來指定例項化後物件的作用域。更多的屬性看下錶:

屬性 描述
class 指定用來建立 bean 的 bean 類。
name bean唯一性識別符號。在基於 XML 的配置元資料中,你可以使用 id或 name 屬性來指定 bean 識別符號。
scope 指定由特定的 bean 定義建立的物件的作用域,預設值為singleton(單例模式)
constructor-arg 它是用來注入依賴關係的,並會在接下來的章節中進行討論。
properties 它是用來注入依賴關係的,並會在接下來的章節中進行討論。
autowiring mode 它是用來注入依賴關係的,並會在接下來的章節中進行討論。
lazy-initialization mode 延遲初始化的 bean 告訴 IoC 容器在它第一次被請求時,而不是在啟動時去建立一個 bean 例項。
initialization 方法 在 bean 的所有必需的屬性被容器設定之後,呼叫回撥方法。它將會在 bean 的生命週期章節中進行討論。
destruction 方法 當包含該 bean 的容器被銷燬時,使用回撥方法。它將會在 bean 的生命週期章節中進行討論。

Bean 的作用域

上面講過用scope屬性指定bean的作用域。作用域的值如下表所示:

作用域 描述
singleton 單例模式,每次返回同一個物件。
prototype 每次都new一個新物件並返回。
request 每次HTTP請求都會建立一個新的Bean,該作用域僅適用於WebApplicationContext環境
session 同一個HTTP Session共享一個Bean,不同Session使用不同的Bean,僅適用於WebApplicationContext環境
global-session 一般用於Portlet應用環境,該運用域僅適用於WebApplicat

程式碼例項:

測試程式碼:

public class Test {
    public static void main(String[] args){
        ApplicationContext context = new FileSystemXmlApplicationContext("E:\\GitHub\\Exercises\\javaweb\\Spring02\\src\\main\\resources\\config.xml");
        System.out.println(context.getBean("stu01"));
        System.out.println(context.getBean("stu01"));
    }
}

singleton,scope預設值為singleton,所以可以省略不寫:

<bean id="stu01" class="com.haya.bean.Student"
        scope="singleton">
        <property name="name" value="GGBoy"/>
        <property name="age" value="20"/>
        <property name="sex" value="man"/>
</bean>

[email protected]
[email protected]

可以看出獲取的兩個物件的hash碼相同,可以確認它們是同一個物件。

prototype:

<bean id="stu01" class="com.haya.bean.Student"
    scope="prototype">
    <property name="name" value="GGBoy"/>
    <property name="age" value="20"/>
    <property name="sex" value="man"/>
</bean>

[email protected]
[email protected]

可以看出獲取的兩個物件的hash碼不同,可以確認它們不是同一個物件。

Bean 的生命週期

有兩個生命週期方法init、destroy。類似於建構函式和解構函式(但是init在建構函式之後執行),在例項化物件或銷燬物件時做一些事情。

在Student類中新增以下兩個方法:

public void init(){
    System.out.println("init");
}
public void destroy(){
    System.out.println("destroy");
}

在測試類中執行如下程式碼

public class Test {
    public static void main(String[] args){
        AbstractApplicationContext context = new FileSystemXmlApplicationContext("E:\\GitHub\\Exercises\\javaweb\\Spring02\\src\\main\\resources\\config.xml");
        Student student = (Student) context.getBean("stu01");
        System.out.println(student.getAge());
        context.registerShutdownHook(); //關閉context
    }
}

init
20
destroy

需要注意的是,當作用域為prototype 時, Spring 不會負責銷燬容器中的物件,所以不會執行destroy方法。