- 在 porm.xml 中添加依赖
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.2.2</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.2.2</version>
</dependency>
- 2.在 Application 同级目录中添加 Swagger2 的配置类
@Configuration
@EnableSwagger2
public class Swagger2 {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(getApiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("org.xiaocai.web.controller"))
.paths(PathSelectors.any())
.build();
}
private ApiInfo getApiInfo() {
return new ApiInfoBuilder()
.title("小菜在使用swagger")
.description("这是第一个尝试")
.version("1.0")
.build();
}
}
注意需要配置扫描Controller路径 .apis(RequestHandlerSelectors.basePackage("org.xiaocai.web.controller"))
- 在 Controller 中添加需要的文档说明
@RestController
public class CityRestController {
@Autowired
private CityService cityService;
@ApiOperation(value="查找城市", notes="根据城市名查找城市")
@RequestMapping(value = "/api/city", method = RequestMethod.GET)
public City findOneCity(@ApiParam(name = "cityName", value = "城市名", required = true ) @RequestParam(value = "cityName", required = true) String cityName) {
return cityService.findCityByName(cityName);
}
}
-
- 在浏览器中验证
打开:
http://localhost:8080/swagger-ui.html显示