1、在application.yml定义属性
user:
username: zhangsan
age: 18
sex: 男
2、一般获取配置文件的属性在service层
package com.xiaomin.wechat_brn.test;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
@Service
public class UserService {
@Value("${user.username}")
private String username;
@Value("${user.age}")
private int age;
@Value("${user.sex}")
private String sex;
public String getUserInfo(){
return "姓名:"+username+"年龄:"+age+"性别:"+sex;
}
}
3、Controller层使用
package com.xiaomin.wechat_brn.controller;
import com.xiaomin.wechat_brn.test.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class TestController {
@Autowired
private UserService userService;
@RequestMapping("/hello")
@ResponseBody
public String fun(){
String userInfo = userService.getUserInfo();
return userInfo;
}
}
4、测试
![](https://i-blog.csdnimg.cn/blog_migrate/957ddb5031a6734d3ef25002b9faeb46.png)