本文教大家如何在Spring Boot + Spring Security 项目中导入 Swagger3 自动生成接口文档
1. 导入依赖
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-boot-starter</artifactId>
<version>3.0.0</version>
</dependency>
2. 配置 SwaggerConfig
package com.example.demo.config;
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.oas.annotations.EnableOpenApi;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
@Configuration
@EnableOpenApi
public class SwaggerConfig {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.OAS_30)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.example.demo.controller"))
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("Swagger3 RESTful API")
.version("1.0")
.description("CHAOS_ORDER's 管理系统")
.build();
}
}
3. 配置 application.properties
spring.mvc.pathmatch.matching-strategy=ant_path_matcher
4. 配置 WebSecurityConfig
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
...
private static final String[] AUTH_WHITELIST = {
"/authenticate",
"/swagger-resources/**",
"/swagger-ui/**",
"/v3/api-docs",
"/webjars/**"
};
...
@Override
protected void configure(HttpSecurity http) throws Exception {
...
http.authorizeRequests().antMatchers(AUTH_WHITELIST).permitAll();
...
}
...
5. 修改 ResponseAdvice 的注解 @RestControllerAdvice 的生效包
如果你和我一样,做了统一返回数据处理的话,需要修改一下注解
@RestControllerAdvice(basePackages = "com.example.demo")
public class ResponseAdvice implements ResponseBodyAdvice<Object> {
@Resource
ObjectMapper objectMapper;
@Override
public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
return true;
}
@SneakyThrows
@Override
public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
if (body instanceof String) {
return objectMapper.writeValueAsString(ApiResponse.success(body));
}
if (body instanceof ApiResponse) {
return body;
}
return ApiResponse.success(body);
}
}
如此 5 步,便可以正常使用 Swagger3 来生成文档了,默认路径 IP:PORT/swagger-ui/
|