Introduction to the

This project mainly uses Spring Boot2.0 +Swagger2 to test restful interfaces in the background to realize dynamic updates. When the interface in the background is modified, Swagger can automatically update without maintaining the interface for testing.

  • The source address
    • GitHub:github.com/yundianzixu…
  • Union official number: IT combat alliance
  • Our community: 100boot.cn

One small tool, welcome to use and Star support, if you encounter problems in the process of using, you can put forward an Issue, I will try my best to improve the Starter

Version,

  • Spring the Boot: 2.0.4
  • Swagger2:2.7.0

steps

Step 1: download the SpringBoot2.0 project

  • GitHub address: github.com/yundianzixu…
  • Reference: www.jianshu.com/p/7dc2240f0…

Step 2: Add maven dependencies

< the 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 > < the dependency > < groupId > org.. Apache tomcat. Embed < / groupId > <artifactId>tomcat-embed-jasper</artifactId> </dependency> <! <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-tomcat</artifactId> <scope>provided</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency>Copy the code

Step 3: Application. properties Add swagger configuration

# Start Swagger service
swagger.enable=true
Copy the code

Step 4: Configure Swagger with annotations

@Configuration
@EnableSwagger2
public class Swagger2Config {
    public static final String BASE_PACKAGE = "com.itunion";
    @Value("${swagger.enable}")
    private boolean enableSwagger;
    @Bean
    public Docket createRestApi() {
        returnNew Docket (DocumentationType SWAGGER_2). ApiInfo (apiInfo ()) / / production environment is safe to close the swagger. The enable (enableDirectModelSubstitute (Timestamp. Class, DirectModelSubstitute (date.class, long.class).select() // Scan the package path of the interface, Don't forget to change your own apis (RequestHandlerSelectors. BasePackage (BASE_PACKAGE)). The paths (PathSelectors. Any ()). The build (); } private ApiInfoapiInfo() {        return new ApiInfoBuilder()
            .title("Swagger RESTful APIs")
            .description("Swagger API Service")
            .termsOfServiceUrl("http://swagger.io/")
            .contact(new Contact("Swagger"."127.0.0.1"."[email protected]"))
            .version("1.0") .build(); }}Copy the code

note

  • Swagger should be disabled after the normal project goes online, so a configuration enableSwagger is added here
  • You can use directModelSubstitute to do some of the desired type conversions

Step 5: Create the user entity class UserInfo

public class UserInfo {
    @ApiModelProperty("Number")
    private Long id;
    @ApiModelProperty("Username")
    private String userName;
    @ApiModelProperty("Name")
    private String firstName;
    @ApiModelProperty("Name")
    private String lastName;
    @ApiModelProperty("Email")
    private String email;
    @ApiModelProperty(hidden = true@jsonignore private String password; @ApiModelProperty("State") private Integer userStatus; /** get,set/ * *}Copy the code

Step 6: Write a Controller for the home page

@Api(value = "Home page", description = "Home page")
@RequestMapping("/")
@RestController
public class IndexController {
    @ApiOperation(value = "Hello Spring Boot", notes = "Hello Spring Boot")
    @RequestMapping(value = "/", method = RequestMethod.GET)
    public String index() {
        return "Hello Spring Boot";
    }
    @ApiOperation(value = "API page", notes = "Interface List")
    @RequestMapping(value = "/api", method = RequestMethod.GET)
    public void api(HttpServletResponse response) throws IOException {
        response.sendRedirect("swagger-ui.html"); }}Copy the code
  • To facilitate access to the Swagger UI page, we made a redirection API to make it easier

Step 7: Write a Controller for login

@Api(value = "User", description = "User")
@RequestMapping("/userInfo")
@RestController
public class UserInfoController {
    @ApiOperation(value = "Login Interface - Multi-value Transfer Mode", notes = "Enter a username and password to log in.")
    @ApiResponses(value = {
            @ApiResponse(code = 200, message = "OK", response = UserInfo.class, responseContainer = "userInfo"),
            @ApiResponse(code = 405, message = "Wrong account name or password")
    })
    @ApiImplicitParam(name = "map", value = "{\"userName\":\"JackMa\",\"passWord\":\"123\"}")
    @RequestMapping(value = "loginForMap", method = RequestMethod.POST, produces= MediaType.APPLICATION_JSON_UTF8_VALUE)
    ResponseEntity<UserInfo> loginForMap(@RequestBody Map<String, String> map) {
        if(! map.get("userName").equalsIgnoreCase("JackMa") | |! map.get("passWord").equalsIgnoreCase("123")) {
            return ResponseEntity.status(HttpStatus.METHOD_NOT_ALLOWED).build();
        }
        UserInfo user = new UserInfo();
        user.setId(1L);
        user.setUserName("JackMa");
        user.setFirstName("Horse");
        user.setLastName("Cloud");
        user.setEmail("[email protected]");
        user.setUserStatus(1);
        return ResponseEntity.ok(user);
    }

    @ApiOperation(value = "Login Interface - Multi-value Transfer mode", notes = "Enter a username and password to log in.")
    @ApiResponses(value = {
            @ApiResponse(code = 200, message = "OK", response = UserInfo.class, responseContainer = "userInfo"),
            @ApiResponse(code = 405, message = "Wrong account name or password")
    })
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userName",value = "Username", required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "passWord",value = "Password", required = true, dataType = "string",paramType = "query"),
    })
    @RequestMapping(value = "loginForParams", method = RequestMethod.POST, produces= MediaType.APPLICATION_JSON_UTF8_VALUE)
    ResponseEntity<UserInfo> loginForMap(@RequestParam String userName, @RequestParam String passWord) {
        if(! userName.equalsIgnoreCase("JackMa") | |! passWord.equalsIgnoreCase("123")) {
            return ResponseEntity.status(HttpStatus.METHOD_NOT_ALLOWED).build();
        }
        UserInfo user = new UserInfo();
        user.setId(1L);
        user.setUserName("JackMa");
        user.setFirstName("Horse");
        user.setLastName("Cloud");
        user.setEmail("[email protected]");
        user.setUserStatus(1);
        returnResponseEntity.ok(user); }}Copy the code

note

  • Two different data transfer methods are implemented using Params and Param
  • It is recommended to use Spring’s ResponseEntity class for uniform return results
  • Swagger’s support for Response Code is good, we can list all possible exception codes one by one, which is convenient for handling exceptions when docking

Step 8: Start running

http://127.0.0.1:8081/api
Copy the code

note

  • The port number is configured by yourself

As shown below:

Step 9: Execute

contributors

More exciting content can pay attention to “IT combat alliance” public number oh ~~~