Swagger: Teach you step by step how to configure swagger in idea from scratch, complete with graphic version.

Swagger is a set of open source tools and frameworks for designing, building, documenting, and consuming RESTful web services. It allows development teams to design, build, and test APIs and provides easy-to-understand documentation so developers and consumers can quickly understand and use the API. Swagger is commonly used with various programming languages ​​and frameworks to simplify the development and maintenance process of APIs.

Step one: Use IDEA to build a Spring Boot project (enough to start from 0)

1. File==>Project==>New project, create a new Spring project here

2. Next, select the version and required dependencies, then complete the project creation, go in and wait for the dependencies to be loaded.

3. If nothing else goes wrong, the created project file directory should be:

Step 2: Add Swagger related dependencies

1. Open the pom.xml file above and add the following three dependencies:

<dependency>
   <groupId>io.springfox</groupId>
   <artifactId>springfox-swagger2</artifactId>
   <version>2.7.0</version>
</dependency>
<dependency>
   <groupId>io.springfox</groupId>
   <artifactId>springfox-swagger-ui</artifactId>
   <version>2.7.0</version>
</dependency>
<dependency>
  <groupId>com.github.xiaoymin</groupId>
  <artifactId>knife4j-spring-boot-starter</artifactId>
  <version>2.0.8</version>
</dependency>

2. Then prepare to configure application.properties: mainly some configurations of JDBC

#将路径替换为你的路径
spring.datasource.url=jdbc:mysql://localhost:3306/food?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2B8&useSSL=false&allowMultiQueries=true
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driverClassName = com.mysql.cj.jdbc.Driver

Then prepare the configuration file:

3. Create a new config folder under com.swaggertest, and then create SwaggerConfig and WebMvcConfigurer< /span>FilesJAVATwo

4. ClickSwaggerConfig, the configuration is as follows. After you paste it, it will most likely be all red. You need to import classes one by one. If you find that you cannot import classes, that is you The dependencies have not been loaded. Right-click the pom, select meaven and then reconstruct

@Configuration
@EnableSwagger2
public class SwaggerConfig {
    @Bean
    public Docket docket() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                // 通过.select()方法,配置扫描哪些API接口,RequestHandlerSelectors配置如何扫描接口
                .select()
                //any() // 扫描所有,项目中的所有接口都会被扫描到
                //none() // 不扫描接口
                // 通过方法上的注解扫描,如withMethodAnnotation(GetMapping.class)只扫描get请求
                //withMethodAnnotation(final Class<? extends Annotation> annotation)
                // 通过类上的注解扫描,如.withClassAnnotation(Controller.class)只扫描有controller注解的类中的接口
                //withClassAnnotation(final Class<? extends Annotation> annotation)
                //basePackage(final String basePackage) // 根据包路径扫描接口
                .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))  //添加ApiOperiation注解的被扫描
                .paths(PathSelectors.any())
                .build();
    }
    private ApiInfo apiInfo() {
        Contact contact = new Contact("加洛斯", "666", "[email protected]");
        return new ApiInfo(
                "文档标题",
                "文档标题的描述",
                "版本1.0",
                "urn:tos",
                contact,
                "Apache 2.0",
                "http://www.apache.org/licenses/LICENSE-2.0",
                new ArrayList());
    }
}

If the situation is similar to the following, reconstruct the pom file

Right-click pom, select maven at the bottom, reload the project, and then the following will appear where you can import classes

 Please note this, select service:

 After configuration, it is as shown below:

5. Next configureWebMvcConfigurer

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
@Configuration
public class WebMvcConfigurer extends WebMvcConfigurationSupport {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {

        registry.addResourceHandler("/**").addResourceLocations("classpath:/static/");

        /** 配置knife4j 显示文档 */
        registry.addResourceHandler("doc.html")
                .addResourceLocations("classpath:/META-INF/resources/");
        /**
         * 配置swagger-ui显示文档
         */
        registry.addResourceHandler("swagger-ui.html")
                .addResourceLocations("classpath:/META-INF/resources/");
        /** 公共部分内容 */
        registry.addResourceHandler("/webjars/**")
                .addResourceLocations("classpath:/META-INF/resources/webjars/");
    }
}

At this point, the preparation work is almost done, but there will be some errors in the future, and we will solve them one by one when we encounter them.

Step 3: Start SpringBoot

1. Start the springboot startup class and visithttp://localhost:8080/doc.html to see the following interface document

 2. Visithttp://localhost:8080/swagger-ui.html to see the following interface document

You may also encounter: The solution is to try using Google Chrome. Unfortunately, Microsoft’s own browser doesn’t know what’s going on.

Of course, you may also encounter the following situations:

You will see a lot of people on the Internet saying that your startup class is in the wrong location. You can check the location, but it is probably useless. The most useful way is to check the three dependencies above, two swagger and one knife4j in the pom file. Have you added and added a sentence in application.properties: spring.mvc.pathmatch.matching-strategy=ant_path_matcher

At this point, the configuration items are completed. Next, let’s take a look at how to use Swagger simply.

Step 4: Use swagger 

1. We create a new entity package, and create a food entity class under this package: Food, and foodtype  Note: Entity classes must follow the camel case nomenclature. To follow the little camel case nomenclature, be sure to follow the little camel case nomenclature! !

Otherwise, the value of @ApiModelProperty will not be displayed.

Annotation introduction: @ApiModel(value = "category name") Acts on the entity class @ApiModelProperty acts on the attributes of the entity class (Know these two for now That’s it, I’ll study the rest after learning the configuration)

@Data
@ApiModel(value = "食物类Model")
public class food {
    @ApiModelProperty(value = "食物ID")
    private String foodId;
    @ApiModelProperty(value = "食物名称")
    private String foodName;
    @ApiModelProperty(value = "食物种类ID")
    private String foodTypeId;
    @ApiModelProperty(value = "食物种类名")
    private String foodTypeName;

    public food(String foodId, String foodName, String foodTypeId, String foodTypeName) {
        this.foodId = foodId;
        this.foodName = foodName;
        this.foodTypeId = foodTypeId;
        this.foodTypeName = foodTypeName;
    }
}

@Data
@ApiModel(value = "食物种类Model")
public class foodtype {
    @ApiModelProperty(value = "食物种类ID")
    private String foodTypeId;
    @ApiModelProperty(value = "食物种类名")
    private String foodTypeName;
    @ApiModelProperty(value = "食物种类所属列表")
    private List<food> foodLists;
}

2. Create a new foodcontroller under the Controller package, and then configure the relevant annotations. Also configure the following annotations @Api and @ApiOperation (the specific use of the annotations will be explained in future studies. You can read other articles by other experts. I won’t go into details here. )

@RestController
@Api(value = "食物Controller", tags = { "获取食物相关接口" })
@RequestMapping(value = "/food")
public class foodController {

    @ApiOperation(value = "获取食物种类类")
    @GetMapping("/getFoodtype")
    public foodtype test2() throws Exception {

        return null;
    }

    @ApiOperation(value = "获取食物类")
    @GetMapping("/getFood")
    public List<food> test1() throws Exception {
        //使用构造函数模拟一个查询的数据方便测试
        food food = new food("1", "锅包肉","1", "肉类");
        List<food> foodList = new ArrayList<food>();
        foodList.add(food);
        return foodList;
    }
}

3. At this point, our annotations are set up. Next, let’s see the effect. Visit:http://localhost:8080/doc.html#/home        We can first see the Model

The Model here is only displayed when we use it in the @ApiOperation annotation in the Controller. If you define a Model but the ApiOperation annotation in the Controller layer does not use this Model, it will not be displayed here. We Let’s see the effect:

Next, look at the Controller layer. You can see that there are two interfaces we just defined:

You can see that the function is very powerful. Let's take a look at the test of the interface. We just simulated one using the constructor and see how it returns:

At this point, our basic Swagger has been successfully built, but it is not enough to just use these in the actual development process. I will explain the commonly used Swagger annotations to everyone later. If you encounter any difficulties in building Swagger, you are welcome. Please leave a message and give it a like if you find it useful. Thank you! ! ! ! !

Guess you like

Origin blog.csdn.net/jialuosi/article/details/132871295