Spring boot and Swagger2 build RESTful API documentation

1. What is swagger ?

  • Swagger is a tool that is convenient for API documentation, and can be easily matched with springMVC programs.

2. The use of swagger in springboot

2.1 Build the spring project project

  • Build a maven project of springbot whose project name is swagger

2.2. Complete the basic logic code

Project basic structure


Introduce lombok

		<dependency>
			<groupId>org.projectlombok</groupId>
			<artifactId>lombok</artifactId>
			<version>1.16.14</version>
		</dependency>

/**
 * TODO class describing users
 *
 * @author honghe
 */

@Data
@Builder
public class User {
    private Long id;
    private String username;
    private String password;
}

/**
 * TODO class description
 *
 * @author honghe
 */
public interface UserService {

    User findUserById(Long id);


    List<User> findUserByName(String name);
}
/**
 * TODO class description
 *
 * @author honghe
 */
@Service
public class UserServiceImpl implements UserService {

    @Override
    public User findUserById(Long id) {
        return User.builder().id(id).username("admin"+id.toString()).password("123456").build();
    }

    @Override
    public List<User> findUserByName(String name) {
        List<User> users = new ArrayList<>();
        for (int i = 1; i <6 ; i++) {
            users.add(User.builder().id((long) i).username("admin-"+name).password("123456").build());
        }
        return users;
    }
}

2.3 Configure swagger

pom.xml introduces the swagger package

	<!-- configure swagger-->
		<dependency>
			<groupId>io.springfox</groupId>
			<artifactId>springfox-swagger2</artifactId>
			<version>2.6.1</version>
		</dependency>

		<dependency>
			<groupId>io.springfox</groupId>
			<artifactId>springfox-swagger-ui</artifactId>
			<version>2.6.1</version>
		</dependency>

Create swaggerConfig

/**
 * TODO class description
 *
 * @author honghe
 */
@Configuration
public class Swagger2Config {
    @Bean
    public Docket api() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo (apiInfo ())
                .select()
                .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
                .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("springboot uses swagger to build api documentation")
                .description("Simple and elegant restfun style, http://blog.csdn.net/saytime")
                .termsOfServiceUrl("http://blog.csdn.net/saytime")
                .version("1.0")
                .build();
    }
}

Configure static resource paths

/**
 * TODO class description
 *
 * @author honghe
 */
@Configuration
public class WebMvcConfig extends WebMvcConfigurerAdapter {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");

        registry.addResourceHandler("swagger-ui.html")
                .addResourceLocations("classpath:/META-INF/resources/");

        registry.addResourceHandler("/webjars/**")
                .addResourceLocations("classpath:/META-INF/resources/webjars/");

    }

}

Create a controller configuration access path


/**
 * TODO class description
 *
 * @author honghe
 */
@Api(value="users",description="User related interface")
@RequestMapping("/users")
@Controller
public class UserController {
    @Autowired
    UserService userService;

    /**
     * Query users by ID
     * @param id
     * @return
     */
    @ApiOperation(value="Get user details", notes="Get user details based on the id of the url")
    @ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "Long", paramType = "path")
    @GetMapping("/getUserById")
    @ResponseBody
    public Map<String,Object> findUser(Long id){
        Map<String,Object> result = new HashMap<>();
        try {
            User user = userService.findUserById(id);
            result.put("code",100);
            result.put("user",user);
        }catch (Exception e){
            result.put("code",101);
            result.put("message","Query failed!");
        }
        return result;
    }

    /**
     * Query user list
     * @return
     */
    @ApiOperation(value="Get user list", notes="Get user list")
    @ApiImplicitParam(name = "name", value = "用户民称", required = true, dataType = "Long", paramType = "path")
    @GetMapping("/getUserByName")
    @ResponseBody
    public Map<String,Object> getUserByName(String name){
        Map<String,Object> result = new HashMap<>();
        try {
            List<User> userList = userService.findUserByName(name);
            result.put("code",100);
            result.put("user",userList);
        }catch (Exception e){
            result.put("code",101);
            result.put("message","Query failed!");
        }
        return result;
    }
}

3. Access API Documentation
http://localhost:8080/swagger/swagger-ui.html

git address: https://gitee.com/zhaoershuang/swagger2.git

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325770575&siteId=291194637