hello大家好,今天我就以自身前几天的一个搭建的一个简单的springboot项目集成swagger案例来水一篇文章咯~
前提条件:需要我们先准备好一个能跑的起来的springboot项目~
下面开始按照步骤来引入swagger吧
1.先引入swagger依赖,这个地方我用的是swagger3.0版本,因为我习惯了3.0版本的ui,用起来比较舒服,看着也比较方便,大家可以依据个人爱好来,当然,3.0版本会跟springboot有不兼容的地方,个别的地方我会指出:
3.0版本就比较简单,引入对应的start类就可以,如果是低版本的话可能需要引入另外的依赖
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-boot-starter</artifactId>
<version>3.0.0</version>
</dependency>
如需引入低版本的swagger依赖的可以看下面依赖坐标
<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>
2. 创建swagger类
@Configuration
@EnableOpenApi
public class Swagger2Config {
@Bean
public Docket createRestApi(){
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.itself.mall")) //为当前包下controller生成API文档
//.apis(RequestHandlerSelectors.withClassAnnotation(Api.class)) //为有@Api注解的Controller生成API文档
//.apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class)) //为有@ApiOperation注解的方法生成API文档
//.apis(RequestHandlerSelectors.withMethodAnnotation(ApiModelProperty.class)) //为有@ApiModelProperty注解的方法生成API文档
.paths(PathSelectors.any())
.build();
}
/**
* 构建 api文档的详细信息函数
*/
private ApiInfo apiInfo(){
return new ApiInfoBuilder()
.title("swagger-ui演示接口文档")
.description("self-mall")
.contact(new Contact("小卫不是神","www.小卫不是神.com","***@163.com")) //创建人信息
.version("1.0")
.build();
}
}
后面就是给接口层加上对应的@Api注解、方法上加上对应的@ApiOperation注解等; 是不是挺简单的,其实如果使用的swagger3.0版本的话只做了这些是不够的,这个时候我们会发现项目跑不起来,会报一下错误:
3.这个时候我们需要在swagger的config类中添加以下代码解决项目无法正常启动问题
@Bean
public static BeanPostProcessor springfoxHandlerProviderBeanPostProcessor() {
return new BeanPostProcessor() {
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
if (bean instanceof WebMvcRequestHandlerProvider || bean instanceof WebFluxRequestHandlerProvider) {
customizeSpringfoxHandlerMappings(getHandlerMappings(bean));
}
return bean;
}
private <T extends RequestMappingInfoHandlerMapping> void customizeSpringfoxHandlerMappings(List<T> mappings) {
List<T> copy = mappings.stream()
.filter(mapping -> mapping.getPatternParser() == null)
.collect(Collectors.toList());
mappings.clear();
mappings.addAll(copy);
}
@SuppressWarnings("unchecked")
private List<RequestMappingInfoHandlerMapping> getHandlerMappings(Object bean) {
try {
Field field = ReflectionUtils.findField(bean.getClass(), "handlerMappings");
field.setAccessible(true);
return (List<RequestMappingInfoHandlerMapping>) field.get(bean);
} catch (IllegalArgumentException | IllegalAccessException e) {
throw new IllegalStateException(e);
}
}
};
}
这个时候结束了么,其实并没有~ 这个地方我标注一下,大多数时候我们访问swagger地址的时候都是这个路径 :http://localhost:8080/swagger-ui ,这个时候会发现页面找不到,报404 not fund, 其实在3.0的时候swagger的访问页面的html的位置是在这里,看下图:
所以我们需要在路径后面加上这个名称即访问路径是:http://localhost:8080/swagger-ui/index.html
其实这个时候访问的时候我们熟悉的swagger页面出来了,但是仔细看一下好像有点不对劲,对,我们的接口并没有显示出来,可是我回去看看自己的接口层加上了对应的@Api注解和@ApiOperation注解了,为什么不显示呢?
4.这个时候我们需要在yml配置文件中加上匹配规则
spring:
mvc: # 需要修改MVC的匹配策略,不然会不显示接口
path match:
matching-strategy: ant_path_matcher
这个时候再运行的时候就会发现接口显示出来了,大功告成!
下面我又在代码里加入了一个配置,项目在启动的时候在控制台上输出我们的swagger访问地址,这样我们就很方便的鼠标点击就能在浏览器打开了,配置类如下:
@Component
@Slf4j
public class SwaggerOutPutConfig implements ApplicationListener<WebServerInitializedEvent> {
@Override
public void onApplicationEvent(WebServerInitializedEvent event) {
try {
InetAddress inetAddress = Inet4Address.getLocalHost();
int serverPort = event.getWebServer().getPort();
log.info("项目启动启动成功!接口文档地址: http://"+inetAddress.getHostAddress()+":"+serverPort+"/swagger-ui/index.html");
} catch (UnknownHostException e) {
e.printStackTrace();
}
}
}
还是老样子,喜欢的一键三连,点赞、收藏、转发~