最新版Knife4j在SpringBoot中的使用,美化版Swagger。

1、SpringBoot中引入依赖。

        <dependency>
            <groupId>com.github.xiaoymin</groupId>
            <artifactId>knife4j-spring-boot-starter</artifactId>
            <version>3.0.2</version>
        </dependency>

2、增加Swagger配置类。

@Configuration
@EnableSwagger2
public class SwaggerConfig {

    @Bean(value = "1.web")
    public Docket webAPI(){
        return createDocket("1.web", "com.hello.controller");
    };

    public Docket createDocket(String groupName, String basePackage) {
        Docket docket=new Docket(DocumentationType.SWAGGER_2)
                .enable(true)
                .apiInfo(apiInfo())
                //将日期时间类型全部转为String类型
                .directModelSubstitute(LocalDateTime.class, String.class)
                //将日期类型全部转为String类型
                .directModelSubstitute(LocalDate.class, String.class)
                //将时间类型全部转为String类型
                .directModelSubstitute(LocalTime.class, String.class)
                //分组名称
                .groupName(groupName)
                .select()
                //这里指定Controller扫描包路径
                .apis(RequestHandlerSelectors.basePackage(basePackage))
                .paths(PathSelectors.any())
                .build()
                .globalRequestParameters(generateRequestParameters());
        return docket;
    }

    private List<RequestParameter> generateRequestParameters(){
        RequestParameterBuilder token = new RequestParameterBuilder();
        RequestParameterBuilder language = new RequestParameterBuilder();
        List<RequestParameter> parameters = Lists.newArrayList();
        token.name("Authorization").description("token令牌").in(In.HEADER.toValue()).required(true).build();
        language.name("language").description("语言").in(In.HEADER.toValue()).required(false).build();
        parameters.add(token.build());
        parameters.add(language.build());
        return parameters;
    }


    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("Hello World API")
                .description("Hello World API文档")
                .version("1.0")
                .build();
    }
}

3、在Controller中增加注解。

@RestController
@Slf4j
@RequestMapping("/love")
@Api(value = "love", tags = {"爱你一万年接口"})
public class LoveController {

	@GetMapping("/me")
    @ApiOperation(value = "爱我")
    public Result me() {
        
        return Result.ok();
    }

}

升级了SpringBoot版本2.6以上会报错,配置文件加入:

spring:
  mvc:
    pathmatch:
      matching-strategy: ant_path_matcher

你可能感兴趣的:(spring,boot,后端,java,swagger2)