1. 程式人生 > >Swagger2配置詳解

Swagger2配置詳解

Swagger2.9.2

pom.xml

<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>2.9.2</version>
</dependency>
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>
springfox-swagger-ui</artifactId> <version>2.9.2</version> </dependency>

spring-servlet.xml

<!--swagger2-->
<mvc:resources mapping="swagger-ui.html" location="classpath:/META-INF/resources/"/>
<mvc:resources mapping="/webjars/**" location="classpath:/META-INF/resources/webjars/"
/>
<!--註冊SwaggerConfig--> <bean id="swaggerConfig" class="com.rishiqing.dingtalk.webcrm.util.swager.SwaggerConfig"></bean>

SwaggerConfig.java

@Configuration
@EnableSwagger2
@EnableWebMvc
@ComponentScan(basePackages="com.rishiqing.dingtalk.webcrm.controller.app")
public class SwaggerConfig
{ @Bean public Docket api() { return new Docket(DocumentationType.SWAGGER_2) .select() .apis(RequestHandlerSelectors.any()) .build() .apiInfo(apiInfo()) .securityContexts(securityContexts()) .securitySchemes(securitySchemes()); } private ApiInfo apiInfo() { return new ApiInfoBuilder() .title("CRM專案介面文件") .description("CRM專案介面測試") .version("1.0.0") .termsOfServiceUrl("") .license("") .licenseUrl("") .build(); } private List<ApiKey> securitySchemes() { List<ApiKey> apiKeyList= new ArrayList(); apiKeyList.add(new ApiKey("token", "token", "header")); return apiKeyList; } private List<SecurityContext> securityContexts() { List<SecurityContext> securityContexts=new ArrayList<>(); securityContexts.add( SecurityContext.builder() .securityReferences(defaultAuth()) .forPaths(PathSelectors.regex("^(?!auth).*$")) .build()); return securityContexts; } List<SecurityReference> defaultAuth() { AuthorizationScope authorizationScope = new AuthorizationScope("global", "accessEverything"); AuthorizationScope[] authorizationScopes = new AuthorizationScope[1]; authorizationScopes[0] = authorizationScope; List<SecurityReference> securityReferences=new ArrayList<>(); securityReferences.add(new SecurityReference("token", authorizationScopes)); return securityReferences; } }