通常情況下,在項(xiàng)目中都會(huì)有一些配置類,在配置初始化時(shí)候需要導(dǎo)入yml配置中配置好的值,很多情況下我們都能將簡單類型值注入,如String,Integer,但是對(duì)于List或者M(jìn)ap注入確一知半解。本文主要是講解一下使用何種方式能夠成功注入不同類型數(shù)數(shù)據(jù),并加以區(qū)分。
首先來幾個(gè)例子
package org.jeecg.config;
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import java.util.List;
import java.util.Map;
/**
* Description
* <p>
* </p>
* DATE 2020/4/3.
*
* @author zyq.
*/
@Data
@Component
@ConfigurationProperties(prefix = "test")
public class DemoConfiguration {
/**
* yaml和Properties都支持
* 通過橫線連接的形式注入
* test:
* str-demo1: str-demo1
*/
private String strDemo1;
/**
* yaml和Properties都支持
* 通過小駝峰形式
* test:
* strDemo2: strDemo2
*/
private String strDemo2;
/** yaml和Properties都支持
* 通過下劃線連接注入
* test:
* str_demo3: str_demo3
*/
private String strDemo3;
/**
* yaml支持
* Standard YAML list syntax:
* test:
* list-demo1:
* - demo11
* - demo12
*/
private List<String> listDemo1;
/**
* yaml和Properties配置文件支持
* 數(shù)組形式,Standard list syntax using [ ]
* test:
* list-demo2[0]: demo21
* list-demo2[1]: demo22
*/
private List<String> listDemo2;
/**
* yaml和Properties都支持
* 通過逗號(hào)分隔
* list-demo3: demo31,dem32
*/
private List<String> listDemo3;
/**
* yaml支持
* 通過@Value形式注入失敗, @Value("${test.map-demo1}")
* 直接通過ConfigurationProperties(prefix = "test")配合注入
* test:
* map-demo1:
* key1: value1
* key2: value2
*/
private Map<String,String> mapDemo1;
/**
* yaml和Properties都支持
* 該情況下只能通過@Value的Spel注入
* test:
* map-demo2: "{key1: 'value1', key2: 'value2'}"
*/
@Value("#{${test.map-demo2}}")
private Map<String,String> maps;
}
在上述的例子中主要是對(duì)String、List和Map進(jìn)行對(duì)比試驗(yàn)。
@ConfigurationProperties(prefix = "test")的引入,是的再寫重復(fù)的@Value,能夠?qū)⑴渲弥械臄?shù)據(jù)完全映射。特別是map的使用更加簡單,不需要使用@ValueSpel表達(dá)式,就能搞定映射。
關(guān)于map和list在的代碼中已經(jīng)完全體現(xiàn),并做了詳細(xì)對(duì)比。
當(dāng)然,不使用@Value的情況下,可能我們?cè)诓檎夷骋粋€(gè)配置文件的值的就比較麻煩了。所以還是需要結(jié)合個(gè)人習(xí)慣、公司規(guī)范以及業(yè)務(wù)邏輯上選取最優(yōu)的使用方式。
最后關(guān)于配置文件注解的還有很多騷操作,本文不再一一舉例,參考官方文檔
這里引用一下官方的ConfigurationProperties和Value的對(duì)比

@ConfigurationProperties和@Value