Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

Spring 3 新特性:用 @Value 注入配置項

Spring 3.0 引進的 @Value 註解,讓我們可以把 .properties 檔案裡的鍵值直接注入到 Bean 的屬性上,不必再為了讀一個參數去寫 PropertyPlaceholderConfigurer 加一堆 XML。

步驟一:引入 util 命名空間

在 applicationContext.xml 的 <beans> 節點上宣告 util 命名空間與對應的 schema:

<beans xmlns:util="https://www.springframework.org/schema/util"
       xsi:schemaLocation="https://www.springframework.org/schema/util
       https://www.springframework.org/schema/util/spring-util-3.1.xsd">
</beans>

步驟二:把配置檔掛進容器

<util:properties id="settings"
  location="WEB-INF/classes/META-INF/spring/test.properties" />

這行的作用是把 test.properties 讀成一個名為 settings 的 Map,後續就能用 SpEL 取值。

步驟三:準備配置檔

建立 test.properties,內容只有一行:

test.abc=123

步驟四:在類裡注入

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@RequestMapping("/admin/images")
@Controller
public class ImageAdminController {

    private String imageDir;

    @Value("#{settings['test.abc']}")
    public void setImageDir(String val) {
        this.imageDir = val;
    }
}

這裡的 #{settings['test.abc']} 是 SpEL 表達式:settings 指前面 util:properties 建立的 Map,中括號裡是 key。就這樣,test.abc 的值被注入到 imageDir 中。

順帶一提

@Value 除了 SpEL 寫法,也支援 @Value("${test.abc}") 這種占位符形式,前提是容器裡有對應的 PropertySourcesPlaceholderConfigurer。兩者相比,SpEL 的表達能力更強,可以寫運算式與呼叫方法;純取值場景則占位符更直觀。注入位置也不限於 setter,直接標在欄位或方法參數上都可行,只是標在欄位上會繞過 setter 的檢查邏輯,實務上建議保留 setter 注入以便除錯。

Copyright © Linux教程網 All Rights Reserved