环境依赖
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