swagger对于后端、前端、以及测试的好处就不赘述,下面直接操作。
1.引入maven依赖
<!--使用swagger使接口规范化--> <!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger2 --> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.9.2</version> </dependency> <!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger-ui --> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>2.9.2</version> </dependency>
2.swagger配置类
** * swagger配置类 */ @Configuration @EnableSwagger2 public class SwaggerConfig { @Bean public Docket createRestApi(){ return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo()).select() .apis(RequestHandlerSelectors.basePackage("com.sz")).paths(PathSelectors.any()).build(); } private ApiInfo apiInfo(){ return new ApiInfoBuilder().title("秒杀商品-操作API") .termsOfServiceUrl("#").contact("").version("1.0").build(); } }
3.注册资源处理器
@Configuration public class WebConfig implements WebMvcConfigurer { @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/**").addResourceLocations( "classpath:/static/"); registry.addResourceHandler("swagger-ui.html").addResourceLocations( "classpath:/META-INF/resources/"); registry.addResourceHandler("/webjars/**").addResourceLocations( "classpath:/META-INF/resources/webjars/"); } }
4.在controller中进行整合使用
@Api(value = "秒杀管理") @RestController @RequestMapping(value= "/seckill") public class SeckillController { @Autowired private SeckillService seckillService; @ApiOperation("根据条件查询秒杀商品") @ApiImplicitParams({ @ApiImplicitParam(name = "seckillId",value = "秒杀商品Id", required = true, dataType = "Integer",paramType = "query") }) @GetMapping(value = "/list/{seckillId}") public Seckill listById(@PathVariable Long seckillId){ return seckillService.listById(seckillId); } @ApiOperation("查询出所有秒杀商品") @GetMapping(value = "/listAll") public List<Seckill> listAll(){ List<Seckill> seckills=seckillService.listAll(); return seckills; } }
5.访问http://localhost:8080/项目路径/swagger-ui.html#/
over!