天天看點

SpringBoot中使用@Value取配置檔案中的map配置背景配置内容使用配置類的形式擷取使用@Value的方式擷取

背景

在springboot項目中,使用application.properties配置檔案,然後需要配置一個map類型的配置,然後在程式的其他地方擷取這個配置。

配置内容

fyk.db-script.check-sql.[1-FYK_PROPERTIES-DQL]=select case when exists(select 1 from all_tables t where t.TABLE_NAME = upper('fyk_properties')) then 1 else 0 end as result from dual
fyk.db-script.check-sql.[2-FYK_PROPERTIES-DML-fyk-oauth]=select case when exists(select 1 from fyk_properties t where t.application='fyk-oauth') then 1 else 0 end as result from dual
           

注意:如果Map類型的key包含非字母數字和-的字元,需要用[]括起來,否則不需要使用中括号。

使用配置類的形式擷取

建立一個配置類:

@Data
@ConfigurationProperties(prefix = "fyk.db-script")
public class CheckSqlProperties {
    private Map<String, String> checkSql;
}
           

此時debug代碼,可以看到是取到了配置的值:

SpringBoot中使用@Value取配置檔案中的map配置背景配置内容使用配置類的形式擷取使用@Value的方式擷取

但是,如果把以上取配置的方式,改成@Value的形式:

@Value("${fyk.db-script.check-sql}")
    private Map<String, String> checkSql;
           

此時項目無法啟動,提示找不到該配置。不曉得是不是哪裡錯了,如果有知道的,望指教一二!!!

使用@Value的方式擷取

要使用@Value的方式擷取,首先配置檔案中,配置的方式要改下,如下:

fyk.db-script.check-sql={
           

“1-FYK_PROPERTIES-DQL”:“select case when exists(select 1 from all_tables t where t.TABLE_NAME = upper(‘fyk_properties’)) then 1 else 0 end as result from dual”,

“2-FYK_PROPERTIES-DML-fyk-oauth”:“select case when exists(select 1 from fyk_properties t where t.application=‘fyk-oauth’) then 1 else 0 end as result from dual”

}

注意:如果Map類型的key包含非字母數字和-的字元,需要用引号括起來,否則不需要使用引号(建議都用上引号);value值,都必須要用引号括起來。

在使用該配置的地方,使用@Value的使用擷取:

@Value("#{${fyk.db-script.check-sql}}")
    private Map<String, String> checkSql;
           

此時debug代碼,可以看到是取到了配置的值:

SpringBoot中使用@Value取配置檔案中的map配置背景配置内容使用配置類的形式擷取使用@Value的方式擷取