当前位置:网站首页>Swagger2 easy to use

Swagger2 easy to use

2022-06-11 18:39:00 starriesWEB

newly build springboot project , Check web, Import swagger rely on

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

To write controller

@Controller
public class MyController {
    

    @RequestMapping("/hello")
    @ResponseBody
    public String hello(){
    
        return "hello swagger";
    }
}

To configure Swagger Information

@Configuration
@EnableSwagger2
public class SwaggerConfig {
    

    @Bean
    public Docket docket() {
    
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(this.apiInfo());
    }

    private ApiInfo apiInfo() {
    
        return new ApiInfo("Swagger The title of the ",
                "Swagger Description of ",
                "2.0",
                "https://blog.csdn.net/qq_45722508?type=blog",
                new Contact("starry","https://blog.csdn.net/qq_45722508?type=blog","[email protected]"),
                "Apache 2.0",
                "http://www.apache.org/licenses/LICENSE-2.0",
                new ArrayList<>());
    }
}

Start access , visit /hello, Normal return
visit http://localhost:8080/swagger-ui.html, The information is modified normally
 Insert picture description here

Configure scan interface and switch

@Bean
public Docket docket() {
    
    return new Docket(DocumentationType.SWAGGER_2)
            .apiInfo(this.apiInfo())
            .select()
            // RequestHandlerSelectors  Configure how to scan 
            .apis(RequestHandlerSelectors.basePackage("com.starry.controller"))
            //  Path filtering   Only scan the request path with  /starry/**
			// .paths(PathSelectors.ant("/starry/**"))
            .build();
}
@Bean
public Docket docket() {
    
    return new Docket(DocumentationType.SWAGGER_2)
            .apiInfo(this.apiInfo())
            //  Cannot access from the browser swagger
            .enable(false)
            .select()
            // RequestHandlerSelectors  Configure how to scan 
            .apis(RequestHandlerSelectors.basePackage("com.starry.controller"))
            //  Path filtering   Only scan the request path with  /starry/**
// .paths(PathSelectors.ant("/starry/**"))
            .build();
}

Give Way Swagger In production , Test environment , Don't use when publishing

To configure 3 An environment

  • application-dev.properties
    server.port=8081
    
  • application-prod.properties
    server.port=8082
    
  • application-test.properties
    server.port=8083
    

Judge the environment

@Bean
public Docket docket(Environment environment) {
    
   //  Set up swagger The environment to be opened 
   Profiles profiles = Profiles.of("dev","test");

   //  Determine whether the current environment of the project is the same as the specified environment 
   boolean flag = environment.acceptsProfiles(profiles);

   return new Docket(DocumentationType.SWAGGER_2)
           .apiInfo(this.apiInfo())
           //  If it's production , The test environment starts swagger
           .enable(flag)
           .select()
           // RequestHandlerSelectors  Configure how to scan 
           .apis(RequestHandlerSelectors.basePackage("com.starry.controller"))
           //  Path filtering   Only scan the request path with  /starry/**
// .paths(PathSelectors.ant("/starry/**"))
           .build();
}

application.properties

#  Set up the current environment 
spring.profiles.active=dev

Environment switch to dev,test All can be accessed normally swagger
Environment switch to prop, Cannot display document
 Insert picture description here

Configure packet and receive parameter types

.groupName("starry")

Configure multiple groups , Added Bean that will do

@Bean
public Docket docket1(){
    
    return new Docket(DocumentationType.SWAGGER_2).groupName("A");
}

@Bean
public Docket docket2(){
    
    return new Docket(DocumentationType.SWAGGER_2).groupName("B");
}

@Bean
public Docket docket3(){
    
    return new Docket(DocumentationType.SWAGGER_2).groupName("C");
}

 Insert picture description here
Set the type passed in by the front end

.consumes(new LinkedHashSet<String>(Arrays.asList("application/json","application/xml","application/text")))

 Insert picture description here

@Configuration
@EnableSwagger2
public class SwaggerConfig {
    


    @Bean
    public Docket docket(Environment environment) {
    
        //  Set up swagger The environment to be opened 
        Profiles profiles = Profiles.of("dev","test");

        //  Determine whether the current environment of the project is the same as the specified environment 
        boolean flag = environment.acceptsProfiles(profiles);

        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(this.apiInfo())
                //  If it's production , The test environment starts swagger
                .enable(flag)
                //  Set the type passed in by the front end 
                .consumes(new LinkedHashSet<String>(Arrays.asList("application/json","application/xml","application/text")))
                .groupName("starry")
                .select()
                // RequestHandlerSelectors  Configure how to scan 
                .apis(RequestHandlerSelectors.basePackage("com.starry.controller"))
                //  Path filtering   Only scan the request path with  /starry/**
// .paths(PathSelectors.ant("/starry/**"))
                .build();
    }

    private ApiInfo apiInfo() {
    
        return new ApiInfo("Swagger The title of the ",
                "Swagger Description of ",
                "2.0",
                "https://blog.csdn.net/qq_45722508?type=blog",
                new Contact("starry","https://blog.csdn.net/qq_45722508?type=blog","[email protected]"),
                "Apache 2.0",
                "http://www.apache.org/licenses/LICENSE-2.0",
                new ArrayList<>());
    }
}

Interface notes

newly build User object

public class User {
    

    private String username;
    private String password;

	//getter/setter
}

to controller Add notes to explain

@Api(tags = " User controller")
@RestController
public class MyController {
    

    @ApiOperation(value = "hello")
    @GetMapping("/hello")
    @ApiResponses({
    @ApiResponse(code = 500,message = " internal error "),@ApiResponse(code = 404,message = " Resource not found ")})
    public String hello(@ApiParam(value = " user name ")String name){
    
    	//  Make a deliberate mistake 
 		int i = 1 / 0;
        return "name";
    }

    @ApiOperation(value = " Query the user ")
    @GetMapping("/getUser")
    public User getUser(){
    
        return new User("starry","starry");
    }

    @ApiOperation(value = " pick up information ")
    @PostMapping("/postUser")
    public User postUser(User user){
    
        return user;
    }
}
annotation describe
@Api()tags = “ Document labels ”, consumes = “ Types accepted by the server ”
@ApiOperation Interface specification
@ApiParam Parameter description
@ApiResponses Pass in @ApiResponse Array , Customize the status code and return information

 Insert picture description here  Insert picture description here

Annotate the entity class , Only controller The return value is User when , In the document Models It shows that

@ApiModel(description = " User details ")
public class User {
    
    @ApiModelProperty(value = " user name ")
    private String username;
    @ApiModelProperty(value = " password ")
    private String password;
}
annotation describe
@ApiModeldescription = “ A detailed description of the class ”
@ApiModelProperty Description of the field

 Insert picture description here

原网站

版权声明
本文为[starriesWEB]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/162/202206111817380576.html