When Spring Boot gets configuration data, you can define specific classes or use Map data structures.
Take the following configuration as an example:
student:
scores:
math: 100
physics: 90
sports: 95
Copy the code
Define a specific class
package com.example.demo; import javax.annotation.PostConstruct; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.stereotype.Component; @Component @ConfigurationProperties(prefix = "student.scores") public class StudentScore { private Integer math; private Integer physics; private Integer sports; @postconstruct public void PostConstruct () {system.out.println ("math score: " + math); System.out.println("physics score: " + physics); System.out.println("sports score: " + sports); }}Copy the code
Second, the use ofMap
The data structure
package com.example.demo; import java.util.Map; import javax.annotation.PostConstruct; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.stereotype.Component; @Component @ConfigurationProperties(prefix = "student") public class StudentScore { private Map<String, Integer> scores; public Map<String, Integer> getScores() { return this.scores; } public void setScores(Map<String, Integer> scores) { this.scores = scores; } @PostConstruct public void postConstruct() { for (Map.Entry<String, Integer> entry : scores.entrySet()) { System.out.println(entry.getKey() + "=" + entry.getValue()); }}}Copy the code
Note the value of prefix in the ConfigurationProperties annotation.