Spring Boot - swagger2 整合

swagger官网:https://swagger.io/

一,引入依赖


		
			io.springfox
			springfox-swagger2
			2.8.0
		
		
			io.springfox
			springfox-swagger-ui
			2.8.0
		

		
			javax.xml.bind
			jaxb-api
			2.3.0
		

二,创建配置类

@Configuration
@EnableSwagger2
public class SwaggerConfig {

    @Bean
    public Docket createRestApi(){
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.ingenue.ingenue.controller"))
                .paths(PathSelectors.any())
                .build()
                .securitySchemes(securitySchemes())
                .securityContexts(securityContexts());
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("天真无邪-api文档")
                .description("restfun 接口")
                .contact("macro")
                .version("1.0")
                .build();
    }

    private List securitySchemes() {
        //设置请求头信息
        List result = new ArrayList<>();
        ApiKey apiKey = new ApiKey("Authorization", "Authorization", "header");
        result.add(apiKey);
        return result;
    }

    private List securityContexts() {
        //设置需要登录认证的路径
        List result = new ArrayList<>();
        result.add(getContextByPath("/brand/.*"));
        result.add(getContextByPath("/product/.*"));
        result.add(getContextByPath("/productCategory/.*"));
        return result;
    }

    private SecurityContext getContextByPath(String pathRegex){
        return SecurityContext.builder()
                .securityReferences(defaultAuth())
                .forPaths(PathSelectors.regex(pathRegex))
                .build();
    }

    private List defaultAuth() {
        List result = new ArrayList<>();
        AuthorizationScope authorizationScope = new AuthorizationScope("global", "accessEverything");
        AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
        authorizationScopes[0] = authorizationScope;
        result.add(new SecurityReference("Authorization", authorizationScopes));
        return result;
    }
}

三,测试

@Api(value="/test", tags="测试Swagger接口")
@RestController
@RequestMapping("/testSwagger")
public class TestSwaggerController {

    @ApiOperation(value="展示Swagger接口信息", notes = "展示Swagger接口信息")
    @GetMapping("/show")
    public Object showInfo(){
        return "hello Swagger";
    }
}
http://localhost:8080/swagger-ui.html

你可能感兴趣的:(spring,boot)