SpringFox集成原理
SpringFox用于在SpringMVC中整合Swagger,提供web api文档。
参考:
首先直接上个最简单的demo,
@Configuration @EnableWebMvc @EnableSwagger2 public class SpringfoxConfiguration { @Bean public Docket docket() { return new Docket(DocumentationType.SPRING_WEB); } }
确定在Spring能扫描到此配置类:
<context:component-scan base-package="org.mosmith.springfoxdemo" />
因为Swagger-UI作为访问入口,但里面全是静态资源,获取具体应用的Controller/RequestMapping信息的url都是写死在文件里面的,目前笔者所用的2.6.1版本中,这个configuration url是/configuration/ui(相对于swagger-ui.html),configuratio/ui对应了springfox中的一个Controller/RequestMapping,相关代码如下:
springfox-swagger-common/src/main/java/springfox/documentation/swagger/web/ApiResourceController.java
..... private SecurityConfiguration securityConfiguration; @Autowired(required = false) private UiConfiguration uiConfiguration; Optional.fromNullable(securityConfiguration).or(SecurityConfiguration.DEFAULT), HttpStatus.OK); } @RequestMapping(value = "/configuration/ui") @ResponseBody public ResponseEntity<UiConfiguration> uiConfiguration() {
.......
目前swagger的静态资源作为一个jar包依赖进来,运行时它在我们的classpath中,因此我们配置一下ResourceHandler
@Configuration public class SpringMvcConfig extends WebMvcConfigurerAdapter{ @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/swagger-ui.html**") .addResourceLocations("classpath:/META-INF/resources/swagger-ui.html"); registry.addResourceHandler("/webjars/**") .addResourceLocations("classpath:/META-INF/resources/webjars/"); super.addResourceHandlers(registry); } }
这里就来问题了,因为swagger-ui里面静态资源访问configuration/ui的时候使用的是相对路径,如果你配置了swagger-ui.html映射到/documentation/swagger-html**的话,那么就会访问/documentation/configuration/ui去获取应用信息。但是从上面ApiResourceController可以看到,/configuration/ui是写死在代码里面的,很多同学可能在这里出现了404。当然springfox给出一些解决方案,但一般将swagger-ui.html配置到DispatcherServlet的虚拟目录下面即可。
下面来配置一个json的例子:
@Validate @ApiOperation(value="register user", consumes="application/json", produces="application/json") @RequestMapping(path="/registerUser", method={RequestMethod.POST}, consumes={"application/json"}, produces={"application/json; charset=utf-8"}) public ActionResponse regisetrUser(@RequestBody final UserVo userVo){ final User userToRegister = UserUtils.voToBo(userVo); final User registeredUser = userService.registerUser(userToRegister, userVo.getPassword()); final UserVo registeredUserVo = UserUtils.boToVo(registeredUser); return ok(registeredUserVo); }
XMReport-最懂你的Java报表工具
XMReport-The Best Java Report Engine