赞
踩
注:这种方法适用于对象的参数比较少的情况
使用方法:
添加@Data注解是为了方便测试有没有读取到
application.yml
spring:
test:
name: yuanhaozhe
age: 18
phone: 1763173xxxx
ValueConfig.java
@Configuration
@Data
public class ValueConfig {
@Value("${spring.test.name}")
private String name;
@Value("${spring.test.age}")
private int age;
@Value("${spring.test.phone}")
private String phone;
}
BasicController.java
@Controller
public class BasicController {
@Autowired
private ValueConfig valueConfig;
@RequestMapping("/test_valueConfig")
@ResponseBody
public String valueConfig(){
return "name:".concat(valueConfig.getName()).concat(";age:").concat(String.valueOf(valueConfig.getAge()))
.concat(";phone:").concat(valueConfig.getPhone());
}
}
结果:
在pom文件中添加相应注解:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
注:适用于对象的参数比较多情况下,如果对象的参数比较多情况下。
配置文件同上;
TestConfig.java
@Data
@Configuration
@ConfigurationProperties(prefix = "spring.test")
public class TestConfig {
private String name;
private int age;
private String phone;
}
BasicController.java
@Controller
public class BasicController {
@Autowired
private TestConfig testConfig;
@RequestMapping("/test_config")
@ResponseBody
public String testConfig(){
return "name:".concat(testConfig.getName()).concat(";age:").concat(String.valueOf(testConfig.getAge()))
.concat(";phone:").concat(testConfig.getPhone());
}
}
结果:
如何配置List:
spring:
test:
users:
- name: yuanhaoz
age: 17
phone: 123456
- name: bruce
age: 18
phone: 456789
配置类:
类中的users对应配置文件中的users,可以理解为在配置文件对应前缀下按名字获取属性
@Data
@Configuration
@ConfigurationProperties(prefix = "spring.test")
public class TestConfig {
private List<UserTest>users;
}
List中的对象:
对象中的属性对应配置文件中配置对象的属性
@Data
public class UserTest {
private String name;
private int age;
private String phone;
}
测试:
@Controller
public class BasicController {
@Autowired
private TestConfig testConfig;
@RequestMapping("/test_config")
@ResponseBody
public void testConfig(){
List<UserTest> users = testConfig.getUsers();
for (UserTest user:users) {
System.out.println(user.toString());
}
}
}
结果:
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。