在yml中添加配置
swagger:
enabled: true // true 启用,fasle不起用
使用value 或者@ConfigurationProperties(prefix = "swagger") 注入
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Component;
/**
* @author :si
* @date :2023/2/27
*/
@Component
@Data
@ConfigurationProperties(prefix = "swagger")
public class Swagger2Properties {
private boolean enabled;
}
import com.yssoo.lims.modules.swagger.properties.Swagger2Properties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.ParameterBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.schema.ModelRef;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Parameter;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
/**
* @author User
*/
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Resource private Swagger2Properties swagger2Properties;
@Bean
public Docket createRestApi1() {
return new Docket(DocumentationType.SWAGGER_2)
// 可以选择的名字
.groupName("fs")
.apiInfo(apiInfo())
// 可以指定是否启动
.enable(swagger2Properties.isEnabled())
.select()
// 需要扫描的cntroller
.apis(RequestHandlerSelectors.basePackage("com.yssoo.modules.storage.controller"))
.paths(PathSelectors.any())
.build()
.globalOperationParameters(this.getParameterList());
}
@Bean
public Docket createRestApi2() {
return new Docket(DocumentationType.SWAGGER_2)
.groupName("swg")
.apiInfo(apiInfo())
.enable(swagger2Properties.isEnabled())
.select()
// 需要扫描的cntroller
.apis(
RequestHandlerSelectors.basePackage(
"com.yssoo.lims.modules.swagger.controller"))
.paths(PathSelectors.any())
.build()
.globalOperationParameters(this.getParameterList());
}
private ApiInfo apiInfo() {
// 这些其实没啥用
return new ApiInfoBuilder()
.title("SpringBoot使用Swagger构建api文档")
.description("简单优雅的 restfun 风格 ")
.termsOfServiceUrl("00----")
.version("1.0")
.build();
}
/** 添加head参数配置 */
private List<Parameter> getParameterList() {
ParameterBuilder clientIdTicket = new ParameterBuilder();
List<Parameter> pars = new ArrayList<Parameter>();
// name 是传入的token名字token
clientIdTicket
.name("X-Access-Token")
.description("token令牌")
.modelRef(new ModelRef("string"))
.parameterType("header")
.required(false)
.build(); // 设置false,表示clientId参数 非必填,可传可不传!
pars.add(clientIdTicket.build());
return pars;
}
}