Use @Value in SpringBoot to get the map configuration in the configuration file

background

In the springboot project, use the application.properties configuration file, then you need to configure a map type configuration, and then get this configuration elsewhere in the program.

configuration content

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

Note : If the key of the Map type contains non-alphanumeric and - characters, it needs to be enclosed in [], otherwise it is not necessary to use square brackets.

Get it in the form of configuration class

Create a configuration class:

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

At this point in the debug code, you can see that the configured value has been obtained:
insert image description hereHowever, if the above method of obtaining the configuration is changed to the form of @Value:

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

At this point the project cannot be started, prompting that the configuration cannot be found. I don't know if there is something wrong, if anyone knows, please give me some advice! ! !

Use @Value to get

To use the method of @Value, firstly, in the configuration file, the configuration method needs to be changed, as follows:

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"\
  }

Note : If the key of the Map type contains non-alphanumeric and - characters, it needs to be enclosed in quotation marks, otherwise it is not necessary to use quotation marks (it is recommended to use upper quotation marks); value values ​​must be enclosed in quotation marks.

Where this configuration is used, use the use of @Value to get:

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

At this time, debug the code, and you can see that the configured value is obtained:
insert image description here

Guess you like

Origin blog.csdn.net/fyk844645164/article/details/107897873