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();
}
}
返回值为空
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/133819.html