Spring boot 通過@ConfigurationProperties或@Value注入不同類型的值

通常情況下,在項(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
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容