1,创建好一个SpringBoot程序
项目目录
2,创建实体类对象User
package ink.awz.pojo;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
/**
* @version 1.0
* @Author:杨杰
* @Date:2022/2/23 17:53
*/
@Component
@ConfigurationProperties(prefix = "user")
public class User {
private String username;
private String password;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public String toString() {
return "User{" +
"username='" + username + '\'' +
", password='" + password + '\'' +
'}';
}
}
3,创建配置文件Application.yml
user:
username: yj
password: 123456
4,测试
package ink.awz.controller;
import ink.awz.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @version 1.0
* @Author:杨杰
* @Date:2022/2/23 17:59
*/
@RestController
public class UserController {
@Autowired
private User user;
@RequestMapping("/user")
public User getUser() {
return user;
}
}
注意创建User实例过程需要交给Spring来创建 否则无法获取yml配置中的属性
例如:
package ink.awz.controller;
import ink.awz.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @version 1.0
* @Author:杨杰
* @Date:2022/2/23 17:59
*/
@RestController
public class UserController {
@RequestMapping("/user")
public User getUser() {
return new User();
}
}
返回值为空