`
公园美丽
  • 浏览: 11879 次
社区版块
存档分类
最新评论

Spring Boot :快速开始

 
阅读更多

1. Spring Boot是什么?

Spring Boot 是由 Pivotal 团队提供的全新框架,其设计目的是用来简化新 Spring 应用的初始搭建以及开发过程。该框架使用了特定的方式来进行配置,从而使开发人员不再需要定义样板化的配置。

讲的通俗一点就是Spring Boot并不是一个新的框架,它只是整合和默认实现了很多框架的配置方式。

2. 好处是什么?

最大的好处就是简单、快捷、方便,在Spring Boot之前,我们如果要搭建一个框架需要做什么?

  • 配置web.xml,加载Spring和Spring MVC,加载各种过滤器、拦截器
  • 在配置文件application.xml中配置数据库、配置缓存、配置连接池等等
  • 配置日志文件
  • 配置各种配置文件的读取
  • 配置上下文、配置定时任务
  • 各种各样的配置

笔者手边正好有一个很久之前的项目,当时还是使用的Spring3.x,可以给各位看一下当时一个项目的配置文件有多少:

 

Spring Boot (一):快速开始
 

 

而我如果需要新建一个项目,这里面大量的配置文件都要copy过去,并且重新调试,非常的不方便且浪费时间,当Spring Boot横空出世的时候,这些噩梦都结束了。

Spring Boot的优势:

  • 为所有Spring开发者更快的入门
  • 开箱即用,提供各种默认配置来简化项目配置
  • 内嵌式容器简化Web项目
  • 没有冗余代码生成和XML配置的要求

3. 快速入门

目标设定:构建一个简单的RESTful API并实现对应的单元测试

3.1 工程构建方式

Spring Boot提供两种工程构建方式:

关于创建springcloud项目,目前有两种比较方便的方案,核心都是一样的,大家自行选择自己使用方便的。

方式一:

打开spring的官方链接:

https://start.spring.io/

在 Group 中填入自己的组织,一般填写公司的域名的到写,例如 com.jd 或者 com
.baidu ,这里我直接写 com.springboot

在 Artifact 中填写工程的名称,这里我直接写 spring-boot-quick-start 。

package 选择 jar ,java 选择11(目前最新的LTS版本),至此,基础选择已经全都选完,接下来要开始选择我们使用的 Spring Boot 的组件了。

在 Dependencies 中找到 Spring Web ,选择 Spring Web ,结果如下图:

 

Spring Boot (一):快速开始
 

 

最后点击下方的绿色长条按钮 Generate the project 进行下载,等待下载完成后,直接将压缩包解压导入我们的编辑工具idea里即可。

方式二:

基于 idea 创建,打开 idea ,首先 file->new->project ,选中 Spring Initializr ,这时可以看到右侧让我们选择一个初始化的服务url,默认的就是上面的官方链接,https://start.spring.io/

 

Spring Boot (一):快速开始
 

 

点击 next 下一步,填写和上面一样的 Group 、 Artifact 、 java 版本、 package 方式等信息,继续 next 下一步,选择依赖,和前面的方法的一样,在 Dependencies 中找到 Spring Web ,选择 Spring Web ,点击 next ,选择项目名称和存储路径,点击 finish ,静静等一会,第一个项目 spring-boot-quick-start 就新鲜出炉了~~~

我一般选择第一种方式创建 Spring Boot 项目,这种方式不依赖IDE工具。

3.2 工程结构解析

首先先看一下我们创建的工程结构,如下图:

 

Spring Boot (一):快速开始
 

 

  • pom.xml:maven工程配置文件,主要配置当前工程的一些基本信息,包含我们当前使用的组件,版本等信息。
  • src/main/java下的程序入口:Chapter1Application。
  • src/main/resources下的配置文件:application.properties。
  • src/test/下的测试入口:Chapter1ApplicationTests。

3.3 pom.xml

这里我们重点关注 <dependencies> 标签,这里写明了我们引入的组

Java代码  收藏代码
  1. <dependencies>  
  2.     <dependency>  
  3.         <groupId>org.springframework.boot</groupId>  
  4.         <artifactId>spring-boot-starter-web</artifactId>  
  5.     </dependency>  
  6.   
  7.     <dependency>  
  8.         <groupId>org.springframework.boot</groupId>  
  9.         <artifactId>spring-boot-starter-test</artifactId>  
  10.         <scope>test</scope>  
  11.     </dependency>  
  12. </dependencies>  

 

  • spring-boot-starter-web:Web模块
  • spring-boot-starter-test:测试模块,包括JUnit、Hamcrest、Mockito

3.4 使用 Spring MVC 实现一组对 User 对象的 RESTful API

RESTful API 设计如下:

请求类型 URL 功能

GET / 查询用户列表
POST / 创建User
GET /{id} 根据 url 中的 id 获取 user 信息
PUT /{id} 根据 id 更新用户信息
DELETE /{id} 根据 id 删除用户信息

注意:RESTful接口在设计的时候应该遵循标准的方法以及语义,这些语义包含了安全性和幂等性等方面的考量,例如GET和HEAD请求都是安全的, 无论请求多少次,都不会改变服务器状态。而GET、HEAD、PUT和DELETE请求都是幂等的,无论对资源操作多少次, 结果总是一样的,后面的请求并不会产生比第一次更多的影响。

下面列出了GET,DELETE,PUT和POST的典型用法:

GET

  • 安全且幂等
  • 获取表示
  • 变更时获取表示(缓存)

POST

  • 不安全且不幂等
  • 使用服务端管理的(自动产生)的实例号创建资源
  • 创建子资源
  • 部分更新资源
  • 如果没有被修改,则不过更新资源(乐观锁)

PUT

  • 不安全但幂等
  • 用客户端管理的实例号创建一个资源
  • 通过替换的方式更新资源
  • 如果未被修改,则更新资源(乐观锁)

DELETE

  • 不安全但幂等
  • 删除资源

用户Model类如下:

Java代码  收藏代码
  1. public class UserModel {  
  2.     private Long id;  
  3.     private String name;  
  4.     private int age;  
  5.   
  6.     // 省略 getter 和 setter  
  7. }  

 

REST API 实现类如下:

Java代码  收藏代码
  1. @RestController  
  2. public class UserController {  
  3.   
  4.     // 创建线程安全的Map,用作数据存储  
  5.     static Map<Long, UserModel> users = new ConcurrentHashMap<>();  
  6.   
  7.     /** 
  8.      * 查询用户列表 
  9.      * @return 
  10.      */  
  11.     @GetMapping("/")  
  12.     public List<UserModel> getUserList() {  
  13.         List<UserModel> list = new ArrayList<UserModel>(users.values());  
  14.         return list;  
  15.     }  
  16.   
  17.     /** 
  18.      * 创建User 
  19.      * @param userModel 
  20.      * @return 
  21.      */  
  22.     @PostMapping("/")  
  23.     public UserModel postUser(@ModelAttribute UserModel userModel) {  
  24.         users.put(userModel.getId(), userModel);  
  25.         return users.get(userModel.getId());  
  26.     }  
  27.   
  28.     /** 
  29.      * {id} 根据 url 中的 id 获取 user 信息 
  30.      * url中的id可通过@PathVariable绑定到函数的参数中 
  31.      * @param id 
  32.      * @return 
  33.      */  
  34.     @GetMapping("/{id}")  
  35.     public UserModel getUser(@PathVariable Long id) {  
  36.         return users.get(id);  
  37.     }  
  38.   
  39.     /** 
  40.      * 根据 id 更新用户信息 
  41.      * @param id 
  42.      * @param userModel 
  43.      * @return 
  44.      */  
  45.     @PutMapping("/{id}")  
  46.     public UserModel putUser(@PathVariable Long id, @ModelAttribute UserModel userModel) {  
  47.         UserModel u = users.get(id);  
  48.         u.setName(userModel.getName());  
  49.         u.setAge(userModel.getAge());  
  50.         users.put(id, u);  
  51.         return users.get(userModel.getId());  
  52.     }  
  53.   
  54.     /** 
  55.      * 根据 id 删除用户信息 
  56.      * @param id 
  57.      * @return 
  58.      */  
  59.     @DeleteMapping("/{id}")  
  60.     public String deleteUser(@PathVariable Long id) {  
  61.         users.remove(id);  
  62.         return "success";  
  63.     }  
  64. }  

 

  • @Controller:修饰class,用来创建处理http请求的对象
  • @RestController:Spring4之后加入的注解,原来在@Controller中返回json需要@ResponseBody来配合,如果直接用@RestController替代@Controller就不需要再配置@ResponseBody,默认返回json格式。

可以看一下 @RestController ,可以看到 @RestController 本身就是由 @ResponseBody 和 @Controller 组成的,源码如下:

Java代码  收藏代码
  1. @Target(ElementType.TYPE)  
  2. @Retention(RetentionPolicy.RUNTIME)  
  3. @Documented  
  4. @Controller  
  5. @ResponseBody  
  6. public @interface RestController {  
  7.   
  8.     /** 
  9.      * The value may indicate a suggestion for a logical component name, 
  10.      * to be turned into a Spring bean in case of an autodetected component. 
  11.      * @return the suggested component name, if any (or empty String otherwise) 
  12.      * @since 4.0.1 
  13.      */  
  14.     @AliasFor(annotation = Controller.class)  
  15.     String value() default "";  
  16.   
  17. }  

 

单元测试类如下:

Java代码  收藏代码
  1. @RunWith(SpringRunner.class)  
  2. @SpringBootTest  
  3. public class SpringBootQuickStartApplicationTests {  
  4.   
  5.     private MockMvc mvc;  
  6.   
  7.     @Before  
  8.     public void setUp() throws Exception {  
  9.         mvc = MockMvcBuilders.standaloneSetup(new UserController()).build();  
  10.     }  
  11.   
  12.     @Test  
  13.     public void contextLoads() throws Exception {  
  14.         RequestBuilder request = null;  
  15.   
  16.         // 1、get查一下user列表,应该为空  
  17.         request = MockMvcRequestBuilders.get("/")  
  18.                 .contentType(MediaType.APPLICATION_JSON);  
  19.         mvc.perform(request)  
  20.                 .andExpect(MockMvcResultMatchers.status().isOk())  
  21.                 .andDo(MockMvcResultHandlers.print())  
  22.                 .andReturn();  
  23.   
  24.         // 2、post提交一个user  
  25.         request = MockMvcRequestBuilders.post("/")  
  26.                 .param("id""1")  
  27.                 .param("name""Spring Boot")  
  28.                 .param("age""18")  
  29.                 .contentType(MediaType.APPLICATION_JSON);  
  30.         mvc.perform(request)  
  31.                 .andExpect(MockMvcResultMatchers.status().isOk())  
  32.                 .andDo(MockMvcResultHandlers.print())  
  33.                 .andReturn();  
  34.   
  35.         // 3、get获取user列表,应该有刚才插入的数据  
  36.         request = MockMvcRequestBuilders.get("/")  
  37.                 .contentType(MediaType.APPLICATION_JSON);  
  38.         mvc.perform(request)  
  39.                 .andExpect(MockMvcResultMatchers.status().isOk())  
  40.                 .andDo(MockMvcResultHandlers.print())  
  41.                 .andReturn();  
  42.   
  43.         // 4、put修改id为1的user  
  44.         request = MockMvcRequestBuilders.put("/1")  
  45.                 .param("name""Spring Boot Test")  
  46.                 .contentType(MediaType.APPLICATION_JSON);  
  47.   
  48.         mvc.perform(request)  
  49.                 .andExpect(MockMvcResultMatchers.status().isOk())  
  50.                 .andDo(MockMvcResultHandlers.print())  
  51.                 .andReturn();  
  52.   
  53.         // 5、get一个id为1的user  
  54.         request = MockMvcRequestBuilders.get("/1")  
  55.                 .contentType(MediaType.APPLICATION_JSON);  
  56.   
  57.         mvc.perform(request)  
  58.                 .andExpect(MockMvcResultMatchers.status().isOk())  
  59.                 .andDo(MockMvcResultHandlers.print())  
  60.                 .andReturn();  
  61.   
  62.         // 6、del删除id为1的user  
  63.         request = MockMvcRequestBuilders.delete("/1")  
  64.                 .contentType(MediaType.APPLICATION_JSON);  
  65.   
  66.         mvc.perform(request)  
  67.                 .andExpect(MockMvcResultMatchers.status().isOk())  
  68.                 .andDo(MockMvcResultHandlers.print())  
  69.                 .andReturn();  
  70.   
  71.         // 7、get查一下user列表,应该为空  
  72.   
  73.         request = MockMvcRequestBuilders.get("/")  
  74.                 .contentType(MediaType.APPLICATION_JSON);  
  75.   
  76.         mvc.perform(request)  
  77.                 .andExpect(MockMvcResultMatchers.status().isOk())  
  78.                 .andDo(MockMvcResultHandlers.print())  
  79.                 .andReturn();  
  80.   
  81.     }  
  82.   
  83. }  

 

启动测试类,控制台打印如下,这里仅截取一段内容做展示:

Java代码  收藏代码
  1. MockHttpServletRequest:  
  2.       HTTP Method = POST  
  3.       Request URI = /  
  4.        Parameters = {id=[1], name=[Spring Boot], age=[18]}  
  5.           Headers = [Content-Type:"application/json"]  
  6.              Body = <no character encoding set>  
  7.     Session Attrs = {}  
  8.   
  9. Handler:  
  10.              Type = com.springboot.springbootquickstart.controller.UserController  
  11.            Method = public com.springboot.springbootquickstart.model.UserModel com.springboot.springbootquickstart.controller.UserController.postUser(com.springboot.springbootquickstart.model.UserModel)  
  12.   
  13. Async:  
  14.     Async started = false  
  15.      Async result = null  
  16.   
  17. Resolved Exception:  
  18.              Type = null  
  19.   
  20. ModelAndView:  
  21.         View name = null  
  22.              View = null  
  23.             Model = null  
  24.   
  25. FlashMap:  
  26.        Attributes = null  
  27.   
  28. MockHttpServletResponse:  
  29.            Status = 200  
  30.     Error message = null  
  31.           Headers = [Content-Type:"application/json;charset=UTF-8"]  
  32.      Content type = application/json;charset=UTF-8  
  33.              Body = {"id":1,"name":"Spring Boot","age":18}  
  34.     Forwarded URL = null  
  35.    Redirected URL = null  
  36.           Cookies = []  
0
1
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics