SpringBoot整合swagger2

young 477 2021-10-19

依赖

<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>

配置

配置放在配置中心或配置文件

@Component
@ConfigurationProperties(prefix = "swagger")
@Getter
@Setter
public class SwaggerConfiguration {

    private Boolean enabled;
    private String basePath;
    private String basePackage;
    private String title;
    private String description;
    private String version;
    private Boolean tokenEnabled = Boolean.TRUE;
    private Boolean authorizationEnabled = Boolean.FALSE;
    private Boolean visitorIdEnabled = Boolean.FALSE;

}
@EnableSwagger2
@Configuration
public class SwaggerConfig {

    @Resource
    private SwaggerConfiguration swaggerConfiguration;

    @Bean
    public Docket createRestApi() {
		return new Docket(DocumentationType.SWAGGER_2)
            	// 全局配置
				.globalOperationParameters(getGlobalOperationParameters())
            	// swagger 开关
                .enable(swaggerConfiguration.getEnabled())
                .apiInfo(apiInfo())
                .pathMapping(swaggerConfiguration.getBasePath())
                .select()
                // 扫描的路径包
                .apis(RequestHandlerSelectors.basePackage(swaggerConfiguration.getBasePackage()))
                // 指定路径处理PathSelectors.any()代表所有的路径
                .paths(PathSelectors.any())
                .build();
    }

	private ArrayList<Parameter> getGlobalOperationParameters() {
		ArrayList<Parameter> operationParameters = new ArrayList<>();
		if(swaggerConfiguration.getAuthorizationEnabled()){
		Parameter authorization = buildParameter("Authorization", "Authorization from header");
		operationParameters.add(authorization);
		}
		if(swaggerConfiguration.getTokenEnabled()) {
			Parameter token = buildParameter("token", "Token from header");
			operationParameters.add(token);
		}
		if(swaggerConfiguration.getVisitorIdEnabled()) {
			Parameter token = buildParameter("visitorId", "visitorId from header");
			operationParameters.add(token);
		}
		return operationParameters;
	}
	
     // 添加header
	private Parameter buildParameter(String headerName, String description) {
		return new ParameterBuilder().name(headerName).description(description)
				.required(true).allowMultiple(false).modelRef(new 					ModelRef("string")).parameterType("header")
				.order(DEFAULT_PRECEDENCE).build();
	}

	private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title(swaggerConfiguration.getTitle())
                .description(swaggerConfiguration.getDescription())
                .version(swaggerConfiguration.getVersion())
                .build();
    }
}