0.引言及注意事项

Swagger是一个接口文档工具,依照Swagger可以0配置开发接口。不过要注意,Swagger是基于SpringBoot1.47版本开发的,而SpringBoot现在基本都是是2+。

如果要选用restful支持,只能将SpringBoot退出到1+版本。


1.maven引入

<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>

2.Swagger配置文档

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.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2; @Configuration
@EnableSwagger2
public class swaggerConfig {
@Bean
Docket docket(){
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.any())
.paths(PathSelectors.any())
.build()
.apiInfo(new ApiInfoBuilder().description("项目").build());
}
}

3.接口配置

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.just.computer.mathproject.Entity.Advertisement;
import org.just.computer.mathproject.Service.AdvertisementService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController; import java.util.List; @RestController
@Api(tags ="广告")
@RequestMapping("/Advertisement/")
public class AdvertisementController {
@Autowired
AdvertisementService advertisementService; @ApiOperation(value ="获得所有广告")
@GetMapping("/getAllAdvertisement")
public List<Advertisement> getAllAdvertisement(){
return advertisementService.getAllAdvertisement();
}
@ApiOperation(value = "添加广告")
@GetMapping("/addAdvertisement")
public Boolean getAllAdvertisement(@RequestParam String img, @RequestParam String href){
try {
advertisementService.addAdvertisement(img,href);
return true;
}catch (Exception e){
return false;
}
} @ApiOperation(value = "删除广告")
@GetMapping("/deleteAdvertisement")
public Boolean deleteAdvertisementById(Integer id){
try{
advertisementService.deleteAdvertisementById(id);
return true;
}catch (Exception e){
return false;
}
}
}

本地运行后访问这里即可访问

或者到ip:端口/swagger-ui.html

运行结果如下

SpringBoot+Swagger整合-LMLPHP

05-21 13:37