swagger配置

1.maven依赖
(第一个后台/v2/api-do,第二个UI页面引用的jar包,版本2.6.1)
       <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.6.1</version>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.6.1</version>
        </dependency>
2.Swagger配置文件
@Configuration    // 配置注解,自动在本类上下文加载一些环境变量信息
@EnableSwagger2   // 使swagger2生效
@EnableWebMvc
@ComponentScan(basePackages = {“com.enation.app.javashop.xiaochengxu.action.api”})  //需要扫描的包路径
public class SwaggerConfig extends WebMvcConfigurationSupport {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.any())
.paths(PathSelectors.any())
.build();
}
}
3.web.xml配置说明
(说明:Springmvc前端控制器扫描路径增加“/v2/api-docs”,用于扫描Swagger的 /v2/api-docs,否则 /v2/api-docs无法生效,备注spring的映射一定要是/,否则swagger2中需要引入相关静态资源可能会因为找不到而导致页面加载失败。)
<servlet-mapping>
        <servlet-name>spring-servlet</servlet-name>
        <url-pattern>/swagger-resources</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>spring-servlet</servlet-name>
        <url-pattern>/v2/api-docs</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>spring-servlet</servlet-name>
        <url-pattern>/swagger-resources/configuration/ui</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>spring-servlet</servlet-name>
        <url-pattern>/swagger-resources/configuration/security</url-pattern>
    </servlet-mapping>
4.spring-mvc.xml 增加自动扫描Swagger
<!– 配置Swagger相关静态资源 –>
(Spring的url-pattern映射关系为 /:映射到classpath:/META-INF/resources/下的一个jar里面有swagger-ui.html,用于springmvc自动扫描那个模板和相关js)
<mvc:resources location=”classpath:/META-INF/resources/” mapping=”swagger-ui.html”/>
    <mvc:resources location=”classpath:/META-INF/resources/webjars/” mapping=”/webjars/**”/>
5.freemarker拦截的处理办法
// 前台处理器
 if (uri.endsWith(“.html”) && !(uri.indexOf(“swagger”) >= 0)){
        eopProcessor = new FacadeProcessor();
 }
6.Controller中使用注解添加API文档
@RestController
@RequestMapping(“/api/xcx/adv”)
@Api(description = “获取首页广告接口”)
@Validated
public class AdvApiController {
@Autowired
private IAdvManager advManager;@ApiOperation(value = “根据某个广告id获取广告信息接口”, notes = “根据某个广告id获取广告信息”)
@ApiImplicitParams({ @ApiImplicitParam(name = “advid”, value = “广告id”, required = true, paramType = “path”, dataType = “Long”), })
@RequestMapping(value = “/{advid}”, method = RequestMethod.GET)
public Adv detail(@PathVariable Long advid) {return this.advManager.getAdvDetail(advid);

}

}

发表评论