springBoot项目使用swagger自动生成文档详细步骤
首先创建个springBoot项目:
需要注入依赖:
<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>
<dependency>
<groupId>com.github.joschi.jackson</groupId>
<artifactId>jackson-datatype-threetenbp</artifactId>
<version>2.6.4</version>
</dependency>
然后编写swagger的配置类:
@Configuration
public class SwaggerDocumentationConfig {
ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("Swagger 测试")//标题
.description("测试swagger.")//描述
.version("1.0.0")//版本号
.build();
}
@Bean
public Docket customImplementation(){
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.basePackage("com.example.demonow.controller"))//controller的包的位置
.build()
.directModelSubstitute(org.threeten.bp.LocalDate.class, java.sql.Date.class)
.directModelSubstitute(org.threeten.bp.OffsetDateTime.class, java.util.Date.class)
.apiInfo(apiInfo());
}
}
之后我们需要设置下swagger-ui.html的入口:
@Controller
public class HomeController {
@RequestMapping(value = "/")
public String index() {
System.out.println("swagger-ui.html");
return "redirect:swagger-ui.html";
}
}
swagger-ui.html这个页面不需要我们自己去编写。
最后编写我们的controller:
@Api(value = "用户", description = "用户 API")
@Controller
public class MyController {
@ApiOperation(value = "创建用户", nickname = "创建用户api", tags = {"添加用户"}, notes = "这个接口可以用来新增用户.")
@ApiResponses(value = {
@ApiResponse(code = 200, message = "访问成功")})
@RequestMapping(value = "/addUser", produces = {"application/json"},
method = RequestMethod.GET)
@ResponseBody
public String createUser(@ApiParam(value = "用户名", required = true) String username) {
return "666";
}
}
项目启起来之后访问localhost:port(端口号)
结果展示: