1. 简介
在学习了如何快速创建一个Spring Boot项目和简单使用Spring Boot搭建web项目,接下来要学习的是如何将在mvc模式中使用,本文完成了一个RESTful API
+ curd
的简单例子,并使用TestRestTemplate
来进行junit测试。
2. 环境
使用环境参考Spring Boot基础教程汇总中的讲解:详情请点击
3. 快速入门
项目结构
上图是Spring Boot推荐的典型结构,通常建议将应用的main类(Application
)放到其他类所在的包的顶层(root package),并将@EnableAutoConfiguration
注解到你的main类上,其作用是开启自动配置。
The second class-level annotation is @EnableAutoConfiguration. This annotation tells Spring Boot to “guess” how you will want to configure Spring, based on the jar dependencies that you have added. Since spring-boot-starter-web added Tomcat and Spring MVC,the auto-configuration will assume that you are developing a web application and setup Spring accordingly.Starters and Auto-Configuration.
简要概括,@EnableAutoConfiguration
会根据添加的jar包对Spring进行相应的设置,比如你加载了spring-boot-starter-web
,则会开启Spring Mvc的自动配置,在日志中,可以看到加载了tomcat和spring mvc。想了解更多关于@EnableAutoConfiguration
注解,请看一下这篇文章:springboot EnableAutoConfiguration。
采用root package的结构,就可以使用@ComponentScan
而不需要指定basePackage属性,因为默认从Appliacation
由上向下,逐层扫描加了注解的类。
引入依赖
无特别引入其他依赖,该介绍可参考文章创建第一个Spring Boot应用之Hello World中的相关说明。
代码详解
User实体定义:
public class User {
private long id;
private String name;
private String country;
public User(long id, String name, String country) {
this.id = id;
this.name = name;
this.country = country;
}
public User() {
}
// 省略setter和getter
}
UserService定义:实现简单的curd
@Service
public class UserServiceImpl implements UserService{
private static List<User> users;
static {
users = initUser();
}
private static List<User> initUser() {
List<User> users = new ArrayList<>(10);
users.add(new User(1L,"Mac","USA"));
users.add(new User(2L,"HuaWei",