转载本文请标明出处,谢谢!
SpringFox是最新版的Swagger文档生成工具,SpringFox官方文档参见:SpringFox官方参考文档
package focuson.config;
import com.dianrong.labelaggregator.protocol.request.DisplayLabelsRequest;
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;
/**
* @Date 16-3-20 上午11:55
*/
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket docket() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(new ApiInfoBuilder().title("用户查询系统API").description("用户查询系统API Document").build())
.ignoredParameterTypes(UserRequest.class) //忽略“/list”接口参数
.select()
.apis(RequestHandlerSelectors.basePackage("com.dianrong.labelaggregator.controller"))
.paths(PathSelectors.any())
.build();
}
}
其中ignoredParameterTypes的作用后面再将
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.util.StringUtils;
@ComponentScan("focuson.config")//此处会扫描config包,加载配置文件
@SpringBootApplication
public class LabelAggregatorBootstrap {
private static final String PROFILE = "spring.profiles.active";
public static void main(String[] args) {
if (StringUtils.isEmpty(System.getProperty(PROFILE))) {
System.setProperty(PROFILE, "prod");
}
SpringApplication.run(LabelAggregatorBootstrap.class, args);
}
}
package focuson.controller;
import focuson.protocol.response.BaseResponse;
import com.dianrong.labelaggregator.service.UserQueryService;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.validation.Valid;
/**
* @Author Focuson
* @Date 16-9-26 上午10:37
*/
@RestController
@RequestMapping("/user")
public class UserController extends BaseController {
/**
* API 文档地址: http://localhost:8090/swagger-ui.html
*/
@Autowired
private UserQueryService userQueryService;
@ApiOperation(value = "显示标签", httpMethod = "GET")
@ApiImplicitParams(value = {
@ApiImplicitParam(name = "school", value = "学校名称",
required = true, paramType = "query", dataType = "String"),
@ApiImplicitParam(name = "name", value = "姓名",
required = true, paramType = "query", dataType = "String")
})
@ApiResponses(value = {
@ApiResponse(code = 200, message = "成功",
response = UserResponse.class, responseContainer = "List")
})
@GetMapping(path = "/list", produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity queryUsers(
@Valid UserRequest request, BindingResult bindingResult) {
return excute(request, req -> userQueryService.queryUsers(request), bindingResult);
}
}
UserRequest中封装了name和school两个参数,excute方法在BaseController中,此处省略部分代码。
这个问题在上文中已经解决,基本分为两步:
第一步:在配置文件中使用.ignoredParameterTypes(XXX.class)
第二步:在api上方使用@ApiImplicitParams和@ApiImplicitParam注解
spring-boot配置中使用了如下配置,造成Swagger生成的文档空白
@Configuration
@Slf4j
public class WebConfig extends WebMvcConfigurerAdapter {
@Override
public void configureMessageConverters(List> converters) {
try {
converters.add(new GsonConverter().getObject());
} catch (Exception e) {
// Ignore exception
log.warn("Failed to add converter ", e);
}
}
}
解决这类办法需要实现自己的JSON转换
import com.google.common.base.Strings;
import com.google.gson.FieldNamingPolicy;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonToken;
import com.google.gson.stream.JsonWriter;
import springfox.documentation.spring.web.json.Json;
public class MyGson {
private Gson createGson(FieldNamingPolicy policy) {
return new GsonBuilder()
.setFieldNamingPolicy(policy)
//Register SpringFox Json.class adapter
.registerTypeAdapter(Json.class, new SpringfoxJsonToGsonAdapter())
.create();
}
public static class SpringfoxJsonToGsonAdapter implements JsonSerializer {
@Override
public JsonElement serialize(Json src, Type typeOfSrc, JsonSerializationContext context) {
final JsonParser parser = new JsonParser();
return parser.parse(src.value());
}
}
}
参考:解决办法参考链接
解决办法:
Without Spring Boot, you don’t have the luxury of auto-configuration of your resource handlers. Swagger UI adds a set of resources which you must configure as part of a class that extends WebMvcConfigurerAdapter, and is annotated with @EnableWebMvc.
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("swagger-ui.html")
.addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("/webjars/**")
.addResourceLocations("classpath:/META-INF/resources/webjars/");
}