SpringBoot整合Swagger2
环境:
jdk:1.8
springboot:2.7.1
swagger:2.9.2
一、导包
<!--swagger-->
<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>
二、配置
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket docket() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo()) // 一些描述
.groupName("yangsf") // 组名
.enable(true) // true表示启用swagger,开发完成后可以改为false禁用swagger,这个值用配置文件做更好
.select()//接口扫描配置
.apis(RequestHandlerSelectors.basePackage("com.ds.smartstudio.controller")) // 扫描接口
.build();
}
@Bean
public ApiInfo apiInfo() {
return new ApiInfo("智慧工作室API文档",
"智慧工作室后端API",
"1.0",
"https://test.yangsf.vip/",
new Contact("yangsf", "https://test.yangsf.vip/", "877602782@qq.com"),
"Apache 2.0",
"http://www.apache.org/licenses/LICENSE-2.0",
new ArrayList());
}
}
这些东西对应apiInfo里面的东西
当然,配置多个docker也是可以的
三、一些常用的注解
注解 | 作用域 | 详情 |
---|---|---|
@ApiModel | class | 描述实体类 |
@ApiModelProperty | field | 描述实体类属性,可设置例值 |
@Api | class | 描述接口类 |
@ApiOperation | method | 描述接口 |
@ApiParam | Param | 描述接口需要接收的参数,可设置是否必填 |
一些例:
@Getter
@Setter
@ApiModel(value = "User对象", description = "对应User表")
public class User {
@ApiModelProperty("用户名")
private String dsUserName;
}
@RestController
@RequestMapping("/smartstudio/device")
public class DeviceController {
@Autowired
private DeviceService deviceService;
@ApiOperation("该方法用于编辑设备")
@PutMapping
// required = true表示必填
public void updateDevice(@ApiParam(value = "需要一个device实体", required = true) @RequestBody Device device) {
deviceService.updateById(device);
}
}
然后就可以启动服务使用swagger了
http://localhost:8081/swagger-ui.html
有一些注意事项:
-
若是想要在Model里面查看你的实体类,则可以在对应的Controller接口处返回一个实体。
-
使用就是点开对应的接口 -> try it out -> 输入参数 -> Execute,就能在下面的响应中收获数据。
-
若是打开swagger-ui提示找不到,或是无法启动,可在配置文件中加上
spring: mvc: pathmatch: matching-strategy: ant_path_matcher
拓展:
可以加这么一条提示来方便我们访问swagger-ui
@Component
@Slf4j
public class SwaggerPrintConfig implements ApplicationListener<WebServerInitializedEvent> {
@Override
public void onApplicationEvent(WebServerInitializedEvent event) {
try {
//获取IP
String hostAddress = Inet4Address.getLocalHost().getHostAddress();
//获取端口号
int port = event.getWebServer().getPort();
//获取应用名
String applicationName = event.getApplicationContext().getApplicationName();
log.info("项目启动启动成功!接口文档地址: http://"+hostAddress+":"+event.getWebServer().getPort()+applicationName+"/swagger-ui.html");
} catch (UnknownHostException e) {
e.printStackTrace();
}
}
}