First you can define a properties file like this:
- // The file name can be defined by yourself, here named uploaddefine.properties
- upload.image[JPG]=.jpg
- upload.image[PNG]=.png
- upload.office[CSV]=.csv
- upload.office[EXCEL]=.excel
- upload.text[txt]=.txt
- 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:
- @Configuration
- @ConfigurationProperties(prefix = "upload")
- @PropertySource("classpath:uploaddefine.properties")
- public class UploadDefineConfig {
- omitted......
- }
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:
- public static Map<String, String> image = new HashMap<>();
- public static Map<String, String> office = new HashMap<>();
- public static Map<String, String> text = new HashMap<>();
- //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:
- {
- "image": {
- "JPG": ".jpg",
- "PNG": ".png"
- },
- "office": {
- "EXCEL": ".excel",
- "CSV": ".csv"
- },
- "text": {
- "txt": ".txt",
- "epub": ".epub"
- }
- }
可以看到我们的内容已经成功的被读取出来了,很简单吧
如果你不想用这种K-V形式,而是直接一个List<String>获取所有的值的话,也很简单
只要在properties中这样定义即可:
- my.servers[0]=127.0.0.1:8080
- my.servers[1]=127.0.0.1:8081
- my.servers[2]=127.0.0.1:8082
- // In the class file, you need this
- public static List<String> servers = new ArrayList<>();
For small and medium-sized projects, spring boot is highly recommended to stay away from configuration hell