这两天在学习使用Swagger2生成接口文档,项目是SpringBoot项目,由于业务需要在其中使用FastJson作为默认的Json转换以及Security来控制权限,在使用Swagger生成文档时出现了诸多问题:
在生成接口文档的过程中,有部分路径和资源会被调用,我们需要放过这些路径,避免因为权限的问题而导致无法获取接口信息,生成文档。
先看代码:
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers(HttpMethod.OPTIONS,"/**")//忽略OPTIONS 方法
//放过swagger
.antMatchers("/v2/api-docs",
"/configuration/ui",
"/swagger-resources/**",
"/configuration/**",
"/swagger-ui.html",
"/webjars/**");
}
我们需要在SecurityConfig中添加需要忽略的一些静态资源。
同时我们在访问文档时需要访问http://localhost:8080/swagger-ui.html ,那么我们也需要将swagger-ui.html这个路径也放过,由于我是配置在parameter.properties 里的 ,所以 我只需要在里面做简单的调整即可:
#security无需拦截URL
security.noneSecurityPath = /**/login,/**/regester,/**/sendVercode,/**/generateBike,/**/lockBike,/**/swagger-ui.html
这样就可以解决由于Security权限的问题所导致的文档生成失败。
(只可惜我不是因为这个,我一度认为我是这个原因,后来发现不是的,接下来将第二个原因)
第二种情况就是你选择的FastJson版本有问题,因为fastjson版本为1.2.10以上,fastjson 1.2.15以下时,FastJsonHttpMessageConverter没有暴露fastjson对Serializer配置。更新到新版本之后,可以方便我们加入对springfox.documentation.spring.web.json.Json的序列化支持
解决方法:
1、创建自己的SwaggerJsonSerializer。
话不多说,直接上代码:
①SwaggerJsonSerializer.java
public class SwaggerJsonSerializer implements ObjectSerializer, ObjectDeserializer {
public final static SwaggerJsonSerializer instance = new SwaggerJsonSerializer();
@Override
public void write(JSONSerializer serializer, Object object, Object fieldName, Type fieldType, int features) throws IOException {
SerializeWriter out = serializer.getWriter();
Json json = (Json) object;
out.write(json.value());
}
@Override
public T deserialze(DefaultJSONParser parser, Type type, Object fieldName) {
return null;
}
@Override
public int getFastMatchToken() {
return 0;
}
}
②FastJsonHttpMessageConverterEx.java
实现FastJsonHttpMessageConverter的子类,并在构造函数中,加入springfox.documentation.spring.web.json.Json类与SwaggerJsonSerializer的映射关系,使得在转换的时候,碰到springfox.documentation.spring.web.json.Json就使用我们自己实现的SwaggerJsonSerializer来进行转换,具体如下:
public class FastJsonHttpMessageConverterEx extends FastJsonHttpMessageConverter {
public FastJsonHttpMessageConverterEx() {
super();
this.getFastJsonConfig().getSerializeConfig().put(Json.class, SwaggerJsonSerializer.instance);
}
}
最后,在配置文件中用FastJsonHttpMessageConverterEx替换原来的FastJsonHttpMessageConverter即可。
还是附上代码吧!!!
@Bean
public HttpMessageConverters fastJsonHttpMessageConverters(){
FastJsonHttpMessageConverter fastJsonHttpMessageConverter = new FastJsonHttpMessageConverterEx();
HttpMessageConverter> converter = fastJsonHttpMessageConverter;
return new HttpMessageConverters(converter);
}
2、升级你的FastJson版本
这些调整应该可以保证我们能够正常的生成接口文档了~~~~
头疼的一匹~