1. 首先在yml文件中定义对象
yml 的配置
person:
userName : gao
age : 123
2. 新建一个Person的类,加上扫描注解和读取配置文件的注解,配置文件中要填写对象前缀
@Component
@ConfigurationProperties(prefix = "person")
public class Person implements Serializable {
private String userName;
private Integer age;
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
@Override
public String toString() {
return "Person{" +
"userName='" + userName + '\'' +
", age=" + age +
'}';
}
}
- 使用实例
@RestController
public class ShareController {
@Autowired
private UserService userService;
@Autowired
private Person person;
@RequestMapping("share")
public String share() {
return userService.getUserById(1L).toString() + person.getUserName() + person.getAge();
}
}