天天看點

@Value注解分類解析

1.1.1            @Value注解

@Value的作用是通過注解将常量、配置檔案中的值、其他bean的屬性值注入到變量中,作為變量的初始值。

(1)常量注入

@Value("normal")

    private String normal; // 注入普通字元串

    @Value("classpath:com/hry/spring/configinject/config.txt")

    private Resource resourceFile; // 注入檔案資源

    @Value("http://www.baidu.com")

private Resource testUrl; // 注入URL資源

bean屬性、系統屬性、表達式注入@Value("#{}")

bean屬性注入需要注入者和被注入者屬于同一個IOC容器,或者父子IOC容器關系,在同一個作用域内。

    @Value("#{beanInject.another}")

private String fromAnotherBean; // 注入其他Bean屬性:注入beanInject對象的屬性another,類具體定義見下面

@Value("#{systemProperties['os.name']}")

    private String systemPropertiesName; // 注入作業系統屬性

    @Value("#{ T(java.lang.Math).random() * 100.0 }")

private double randomNumber; //注入表達式結果

(3)配置檔案屬性注入@Value("${}")

@Value("#{}")讀取配置檔案中的值,注入到變量中去。配置檔案分為預設配置檔案application.properties和自定義配置檔案

•application.properties。application.properties在spring boot啟動時預設加載此檔案

•自定義屬性檔案。自定義屬性檔案通過@PropertySource加載。@PropertySource可以同時加載多個檔案,也可以加載單個檔案。如果相同第一個屬性檔案和第二屬性檔案存在相同key,則最後一個屬性檔案裡的key啟作用。加載檔案的路徑也可以配置變量,如下文的${anotherfile.configinject},此值定義在第一個屬性檔案config.properties

第一個屬性檔案config.properties内容如下: 

${anotherfile.configinject}作為第二個屬性檔案加載路徑的變量值

book.name=bookName

anotherfile.configinject=placeholder

第二個屬性檔案config_placeholder.properties内容如下:

book.name.placeholder=bookNamePlaceholder

下面通過@Value(“${app.name}”)文法将屬性檔案的值注入bean屬性值,詳細代碼見:

@Component

// 引入自定義配置檔案。

@PropertySource({"classpath:com/hry/spring/configinject/config.properties",

 // 引入自定義配置檔案。${anotherfile.configinject}則是config.properties檔案中的第二個屬性值,會被替換為config_placeholder.properties。

   "classpath:com/hry/spring/configinject/config_${anotherfile.configinject}.properties"})

public class ConfigurationFileInject{

    @Value("${app.name}")

    private String appName; // 這裡的值來自application.properties,spring boot啟動時預設加載此檔案

    @Value("${book.name}")

    private String bookName; // 注入第一個配置檔案config.properties的第一個屬性

    @Value("${book.name.placeholder}")

    private String bookNamePlaceholder; // 注入第二個配置外部檔案屬性

}

自己開發了一個股票智能分析軟體,功能很強大,需要的點選下面的連結擷取:

https://www.cnblogs.com/bclshuai/p/11380657.html

自己開發了一個股票智能分析軟體,功能很強大,需要的點選下面的連結擷取: