Turn: Customize the properties file in spring boot and get the content

 

 

First you can define a properties file like this:

Java code   Favorite code
  1. // The file name can be defined by yourself, here named uploaddefine.properties  
  2. upload.image[JPG]=.jpg  
  3. upload.image[PNG]=.png  
  4. upload.office[CSV]=.csv  
  5. upload.office[EXCEL]=.excel  
  6. upload.text[txt]=.txt  
  7. upload.text[epub]=.epub  

In this file, we define three categories, namely image, office, text

Our goal is to allow the program to automatically read the content of the file we define. The following is the specific implementation.

 

First, the annotations to indicate on the class are:

Java code   Favorite code
  1. @Configuration  
  2. @ConfigurationProperties(prefix = "upload")  
  3. @PropertySource("classpath:uploaddefine.properties")  
  4. public class UploadDefineConfig {  
  5.       omitted......  
  6. }  

 In this way, the program can automatically read our configuration file,

@ConfigurationProperties(prefix = "upload"): read the content prefixed with upload

@PropertySource("classpath:uploaddefine.properties"): defines the location of the properties file to be read

 

Next, we need to read the content into our pre-defined collection:

Java code   Favorite code
  1. public static Map<String, String> image = new HashMap<>();  
  2. public static Map<String, String> office = new HashMap<>();  
  3. public static Map<String, String> text = new HashMap<>();  
  4.   
  5. //Note that you need to add get/set methods, and these two methods cannot be static   

We define Map as static for convenience, you can also use non-static form.

 

Please note that we define the name of each Map object as the name after the prefix in the properties, only in this way can the program automatically add the contents of the properties file to our Map object.

 

At this point, our custom properties file is done! Come and try it!

We fetch this content through an http request, and here is the result returned:

Java code   Favorite code
  1. {  
  2.     "image": {  
  3.         "JPG"".jpg",  
  4.         "PNG"".png"  
  5.     },  
  6.     "office": {  
  7.         "EXCEL"".excel",  
  8.         "CSV"".csv"  
  9.     },  
  10.     "text": {  
  11.         "txt"".txt",  
  12.         "epub"".epub"  
  13.     }  
  14. }  

 可以看到我们的内容已经成功的被读取出来了,很简单吧

 

如果你不想用这种K-V形式,而是直接一个List<String>获取所有的值的话,也很简单

只要在properties中这样定义即可:

Java代码   Favorite code
  1. my.servers[0]=127.0.0.1:8080  
  2. my.servers[1]=127.0.0.1:8081  
  3. my.servers[2]=127.0.0.1:8082  
  4.   
  5. // In the class file, you need this  
  6. public static List<String> servers = new ArrayList<>();  

 

For small and medium-sized projects, spring boot is highly recommended to stay away from configuration hell

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=327069977&siteId=291194637