主启动类:
@SpringBootApplication
//主启动类@SpringBootApplication
public class Springboot1DemoApplication {
public static void main(String[] args) {
SpringApplication.run(Springboot1DemoApplication.class, args);
}
}
application.yml文件
#yml是有层级关系的 1.注意缩进2.key与值之间注意加空格
server:
port: 8091
servlet:
context-path: /
#可以通过yml文件实现对象的属性赋值
user:
id: 1
username: "hello world"
sex: "男"
age: 1
实体类:
@Component
public class User {
@Value("${user.id}")
private Integer id;
@Value("${user.username}")
private String username;
@Value("${user.sex}")
private String sex;
@Value("${user.age}")
private Integer age;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
Controller层(测试运行):
/**
* 只返回json或者字符串,不需要页面跳转(不走视图解析器)
* 用@RestController注解
* @author 墨霄
*
*/
@RestController
public class UserController {
@Autowired
private User user;
@RequestMapping("/user")
public User user() {
return user;
}
}
浏览器地址栏输入:http://localhost:8091/user
返回结果:{“id”:1,“username”:“hello world”,“sex”:“男”,“age”:1}
心得:
1.赋值时不能用user.name,user.name会获取到当前管理员用户名;
2.application.yml可以给对象赋值
3.@RestController注解只能在返回json或者字符串,跳过视图解析器时使用,是@Controller和@ResponseBody组合注解