Swagger3 study notes

Reference https://blog.csdn.net/YXXXYX/article/details/124952856
https://blog.csdn.net/m0_53157173/article/details/119454044

Introduce dependencies

 <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-boot-starter</artifactId>
            <version>3.0.0</version>
        </dependency>

Start class annotation @EnableWebMvc

If you don't add it, you will report an error

@SpringBootApplication
@EnableWebMvc
public class SwaggerApplication {
    
    

    public static void main(String[] args) {
    
    
        SpringApplication.run(SwaggerApplication.class, args);
    }

}

controller

@RestController
@RequestMapping("/user")
public class UserController {
    
    
    @GetMapping("get")
    public String getUser() {
    
    
        return "user";
    }
}

configuration class

@Configuration
@EnableOpenApi
public class SwaggerConfig {
    
    }

start up

Visit http://localhost:8080/swagger-ui/index.html
insert image description here

Configure Swagger's document generation rules

Docket is a configuration class for configuring Swagger's document generation rules. By creating a Docket instance, you can specify the details of the document to be generated, such as the basic information of the API, path rules, request parameters, response information, and so on.

@Configuration
@EnableOpenApi
public class SwaggerConfig {
    
    

    @Bean
    public Docket docket(Environment environment) {
    
    
        Profiles profiles = Profiles.of("dev", "test"); // 设置要显示swagger的环境
        boolean isOpen = environment.acceptsProfiles(profiles); // 判断当前是否处于该环境

        return new Docket(DocumentationType.OAS_30)
                // 文档信息配置
                .apiInfo(apiInfo())
                // 设置是否启动Swagger,通过当前环境进行判断:isOpen
                .enable(isOpen)
                // 配置扫描的接口
//                .select()
                // 配置扫描哪里的接口
//                .apis(RequestHandlerSelectors.basePackage("com.swagger.controller"))
//                // 过滤请求,只扫描请求以/category开头的接口
//                .paths(PathSelectors.ant("/user/**"))
//                .build()
                ;
    }

    private ApiInfo apiInfo() {
    
    
        return new ApiInfoBuilder()
                .title("外卖项目接口文档") // 文档标题
                .description("基本的一些接口说明") // 文档基本描述
                .contact(new Contact("xxxx", "https://blog.csdn.net", "[email protected]")) // 联系人信息
                .termsOfServiceUrl("http://terms.service.url/组织链接") // 组织链接
                .version("1.0") // 版本
                .license("Apache 2.0 许可") // 许可
                .licenseUrl("https://www.apache.org/licenses/LICENSE-2.0") // 许可链接
                .extensions(new ArrayList<>()) // 拓展
                .build();
    }

}
spring:
  profiles:
    active: dev

In development, there are development environment, test environment, and release environment. Swagger documents should not appear in some environments, such as the release environment, which not only occupies memory, but also easily leaks interface information;

How to use public Docket enable(boolean externallyConfiguredFlag)to see if swagger is enabled

Integrate knife4j

Remove the original swagger dependency below

        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-boot-starter</artifactId>
            <version>3.0.0</version>
        </dependency>

join in

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

Remove @EnableOpenApi, replace it with @EnableKnife4j, configure the local resource mapping path, and the Buddha can't access the Knife4j homepage in full

@EnableKnife4j//启用knife4j
@Configuration
//@EnableOpenApi
public class SwaggerConfig implements WebMvcConfigurer {
    
    

    /**
     * 不配置这个访问不了knife4j首页
     * @param registry
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
    
    
        registry.addResourceHandler("doc.html").addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
    }
}

Visit http://localhost:8080/doc.html
insert image description here

upload files

Use the @RequestPart("file") annotation, otherwise the upload file button will not be displayed

    @PostMapping(value = "/upload")
    @ApiOperation("上传")
    public String upload(@RequestPart("file") MultipartFile file) {
    
    
        return "上传成功";
    }

Solve the problem of returning garbled characters

/**
 * 中文乱码解决
 */
@Configuration
public class CharsetConfig implements WebMvcConfigurer {
    
    

    @Bean
    public HttpMessageConverter<String> responseBodyConverter() {
    
    
        return new StringHttpMessageConverter(StandardCharsets.UTF_8);
    }

    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
    
    
        converters.add(responseBodyConverter());
    }

}

Guess you like

Origin blog.csdn.net/Fire_Sky_Ho/article/details/131626032