# 1.RESTfull API简单项目的快速搭建

### ①打开idea，选择**Create New Project**

### ②项目配置，选择**Spring Initializr**，Project SDK选择**1.8**，URL选择默认，不做修改。如下图所示，然后选择**Next**

![](https://3562539340-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LfnT314x6hQ7gJbPKxx%2F-LfnTB6gvTwJcyb-RbKo%2F-LfnTIJxHKlX9-MHQ1pO%2F1.2.png?generation=1558862971369134\&alt=media)

③继续项目配置

![](https://3562539340-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LfnT314x6hQ7gJbPKxx%2F-LfnTB6gvTwJcyb-RbKo%2F-LfnTIK5QH1UtuUOymmF%2F1.3.png?generation=1558862971000166\&alt=media)&#x20;

这里基本都已经自动生成了，简单介绍下：

* Name：项目名称
* Type：我们是Maven构建的，那么选择第一个Maven Project
* Packaging：打包类型，打包成Jar文件
* Java Version：jdk版本，选择1.8
* Language：开发语言，选择Java
* Group：对应pom文件中的groupId，项目组织的唯一标识，对应Java包的结构
* Artifact：对应pom文件的artifactId，项目唯一标识，对应项目名称
* Version：项目版本，对应pom文件的version
* Description：项目描述，对应pom文件的description
* Package：包名

### ④Spring Boot 版本选择，我这里选择了2.0.2，只要勾选Web下的web就可以了，然后**Next**

![](https://3562539340-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LfnT314x6hQ7gJbPKxx%2F-LfnTB6gvTwJcyb-RbKo%2F-LfnTIK7uMWtVgu9_Eas%2F1.4.png?generation=1558862971786913\&alt=media)

### ⑤项目名称和路径，填写完后Finish

![](https://3562539340-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LfnT314x6hQ7gJbPKxx%2F-LfnTB6gvTwJcyb-RbKo%2F-LfnTIK9F037ZYbmkP0I%2F1.5.png?generation=1558862969734892\&alt=media)

### ⑤最后的项目结构

![](https://3562539340-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LfnT314x6hQ7gJbPKxx%2F-LfnTB6gvTwJcyb-RbKo%2F-LfnTIKBvRKZ5TVtPib5%2F1.1.png?generation=1558862970040530\&alt=media)

## ⑥接下来就新建一个rest的Controller

![](https://3562539340-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LfnT314x6hQ7gJbPKxx%2F-LfnTB6gvTwJcyb-RbKo%2F-LfnTIKEWs_qP4K5jmN6%2F1.6.png?generation=1558862969710781\&alt=media)

### ⑦运行启动即可，spring boot中，集成了tomcat，默认运行在8080端口

![](https://3562539340-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LfnT314x6hQ7gJbPKxx%2F-LfnTB6gvTwJcyb-RbKo%2F-LfnTIKG-sj7MF78y_EQ%2F1.7.png?generation=1558862970496352\&alt=media)

## 继续编写IndexController 类，返回Map类型

```java
package com.shuju.example.controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
public class IndexController {

    @RequestMapping(value = "index")
    public String index()
    {
        return "hello world!";
    }

    @RequestMapping(value = "get")
    public Map<String, String> get(@RequestParam  String name) {
        Map<String, String> map = new HashMap<String, String>();
        map.put("name", name);
        map.put("value", "hello world！");
        return map;
    }

}
```

访问：<http://localhost:8080/get?name=aaa>

![](https://3562539340-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LfnT314x6hQ7gJbPKxx%2F-LfnTB6gvTwJcyb-RbKo%2F-LfnTIKIEs5M7-guoKaa%2F1.8.png?generation=1558862970114155\&alt=media)

你会发现直接将我们返回的map格式转成了json

## 继续编写，返回一个对象

新建一个bean目录，并创建User.java

![](https://3562539340-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LfnT314x6hQ7gJbPKxx%2F-LfnTB6gvTwJcyb-RbKo%2F-LfnTIKLzQgslT8C-EfQ%2F1.9.png?generation=1558862970517850\&alt=media)

IndexController中加入新方法

```java
 @RequestMapping(value = "find/{id}/{name}")
public User get(@PathVariable int id, @PathVariable String name) {
    User user = new User();
    user.setId(id);
    user.setName(name);
    user.setDate(new Date());
    return user;
}
```

浏览器中访问

![](https://3562539340-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LfnT314x6hQ7gJbPKxx%2F-LfnTB6gvTwJcyb-RbKo%2F-LfnTIKNgDQ_E0SEEcNd%2F1.20.png?generation=1558862970977023\&alt=media)

自动将对象转成json返回

## 编写测试类

![](https://3562539340-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LfnT314x6hQ7gJbPKxx%2F-LfnTB6gvTwJcyb-RbKo%2F-LfnTIKPjT8JuGDNVWmV%2F1.21.png?generation=1558862971441744\&alt=media)

模拟请求index路径方法

```java
package com.shuju.example;

import com.shuju.example.controller.IndexController;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MockMvcBuilder;
import org.springframework.test.web.servlet.RequestBuilder;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;

import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

@RunWith(SpringRunner.class)
@SpringBootTest
public class DemoApplicationTests {

    private MockMvc mvc;

    @Before
    public void before(){
        this.mvc = MockMvcBuilders.standaloneSetup(new IndexController()).build();
    }

    @Test
    public void contextLoads() throws Exception {

        //　模拟访问　index 请求
        RequestBuilder req = get("/index");
        mvc.perform(req).andExpect(status().isOk()).andExpect(content().string("hello world!"));

    }

}
```

右键运行，完成测试，如不正确会抛出异常。

## 项目打包

这里介绍一个工具，pom.xml加入依赖

```
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-devtools</artifactId>
</dependency>
```

很有用：

1、可以每次修改完保存，自动进行编译

2、打包时可以把依赖包自动打入

注意：

[Intellij热部署插件JRebel](https://blog.csdn.net/weixin_42831477/article/details/82229436) (devtool 是重新打包,局部单个文件的热部署可以使用这个)

[Intellij IDEA 使用Spring-boot-devTools无效解决办法](https://blog.csdn.net/wjc475869/article/details/52442484)

打包的我这里使用Maven插件，pom.xml中加入插件

```
<plugin>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
```

### 使用maven命令打包

```
mvn clean compile //清除之前target编译文件并重新编译
mvn clean package //对项目进行打包(因为配置过插件，所以jar包是可执行的)
mvn clean install //安装项目，然后就可以使用了
```

可以通过自带的maven管理工具代替执行上面的命令

![](https://3562539340-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LfnT314x6hQ7gJbPKxx%2F-LfnTB6gvTwJcyb-RbKo%2F-LfnTIKRs580Q7PeaBpk%2F1.22.png?generation=1558862971723298\&alt=media)

进行完package打包后，项目目录a 出现了target目录

![](https://3562539340-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LfnT314x6hQ7gJbPKxx%2F-LfnTB6gvTwJcyb-RbKo%2F-LfnTIKTwquXT0uHN53g%2F1.23.png?generation=1558862972117889\&alt=media)

其中 demo-0.0.1-SNAPSHOT.jar 就是打包 后的jar包，包括依赖包

直接单独运行测试

```
sudo java -jar demo-0.0.1-SNAPSHOT.jar
```

访问访问测试：<http://localhost:8080/get?name=aaa>

## 资料

[IntelliJ IDEA搭建SpringBoot的小Demo](https://www.cnblogs.com/weizaibug/p/6657077.html)

[Intellij IDEA 打包jar的多种方式](https://legacy.gitbook.com/book/xiaoxiami/spring-boot/edit)

补充：项目打包

项目打包时，动态设置参数，如端口号：

```
sudo java -jar demo-0.0.1-SNAPSHOT.jar --server.port=8888
```

嫌太长server.port,可以再这样设置，意思是$port如果存在，则使用，不存在则使用默认值8070

```
server:
  port: {$port:8070}
```

启动使用参数

```
sudo java -jar demo-0.0.1-SNAPSHOT.jar --server.port=8888
```
