環境依賴
sprint-boot version 2.1.7
java version 1.8
pom.xml 依賴jar包
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
test.properties
username=test
password=123456
info.age=26
看下目錄佈局
TestConfig.java 加載配置的類文件
//prefix 爲空則加載整個配置文件中的 參數
@ConfigurationProperties(prefix = "")
@PropertySource("classpath:test.properties")
//注意必定要註冊
@Component
public class TestConfig {
private String username;
private String password;
private Info info;
public void setInfo(Info info) {
this.info = info;
}
public Info getInfo() {
return info;
}
public String getUsername() {
return username;
}
public String getPassword() {
return password;
}
public void setUsername(String username) {
this.username = username;
}
public void setPassword(String password) {
this.password = password;
}
public static class Info{
private Integer age;
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
@Override
public String toString() {
return "Info{" +
"age=" + age +
'}';
}
}
@Override
public String toString() {
return "TestConfig{" +
"username='" + username + '\'' +
", password='" + password + '\'' +
", info=" + info +
'}';
}
}
HelloController.java 用來測試
@Controller
public class HelloController {
@Autowired
TestConfig testConfig;
@ResponseBody
@GetMapping("/hello")
public String sayHello()
{
//讀取配置
return "age=" + testConfig.getInfo().getAge();
}
@ResponseBody
@GetMapping("username")
public String getUsername()
{
//讀取配置測試
return testConfig.getUsername();
}
}
訪問 http://localhost:8080/hello | http://localhost:8080/username