直接上图,看图说话
- IntelliJ IDEA左上角新建项目
File → New → Project
,选择Spring Initializr,这个操作需要联网,使用默认模板,不联网的没试过
-
给项目命名,选择Java版本和打包方式等
-
选择SpringBoot版本以及需要自动导入的Maven依赖,我这里勾选了两个,已选择的会在如下图右侧列表显示,然后Next生成项目
- 在pom.xml文件中导入swagger依赖,这里用的是swagger2
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.7.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.7.0</version>
</dependency>
- 创建swagger配置类
package com.example.demo;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
/**
* @Author: Juncheng
* @Date: 2021/5/19 16:03
* @Description:
*/
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket productApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.example.demo.controller"))
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("mjc RESTful API")
.description("测试一下springboot配置swagger")
.version("1.0")
.build();
}
}
- 新建一个controller接口进行测试
package com.example.demo.controller;
import com.example.demo.TestJson;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @Author: Juncheng
* @Date: 2021/5/19 16:03
* @Description:
*/
@RestController
@RequestMapping("/test")
@Api(tags = "测试swagger文档")
public class TestController {
@PostMapping("/json")
@ApiOperation("测试接口testJson")
public void testJson(@RequestBody TestJson testJson) {
String myName = testJson.getMyName();
Integer myAge = testJson.getMyAge();
System.out.println(testJson.toString());
}
}
- 在配置文件application.properties配置一下端口
server.port=8081
-
启动测试,浏览器输入http://localhost:8081/swagger-ui.html
-
接口请求参数
-
接口返回值
成功,over!