SpringMvc 3分钟集成swagger2

swagger:restful管理项目API工具

1、引入最新版本的swagger依赖,低版本的有一些bug。如hidden注解的字段不生效

        
        
            io.springfox
            springfox-swagger2
            2.7.0
        
        
            io.springfox
            springfox-swagger-ui
            2.7.0
        
        
            org.mapstruct
            mapstruct
            1.1.0.Final
        
        

2、在spring-mvc.xml中声明swagger配置bean

也可以自定义swagger2Config配置替代上面的配置

自定义配置对应的java类

@Configuration
@EnableSwagger2
public class Swagger2Config extends WebMvcConfigurationSupport {
    @Bean
    public Docket productApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.example.liuyaohua.controller.swagger"))
                //.paths(regex("/product.*"))
                .build();
    }
}
com.example.liuyaohua.controller.swagger为指定swagger管理的包路径,如果指定了在页面中仅显示该包路径下的conrtorller入口

3、在spring-mvc.xml中配置资源文件

	
	

4、controller样例及说明

Name Description
@Api

Marks a class as a Swagger resource.

标识一个类是swagger资源 

@ApiImplicitParam Represents a single parameter in an API Operation.
@ApiImplicitParams A wrapper to allow a list of multiple ApiImplicitParam objects.
@ApiModel

Provides additional information about Swagger models.

对模型(java类)进行说明,如http请求中接收参数

@ApiModelProperty

Adds and manipulates data of a model property.

对模型(java类)中的字段进行说明

@ApiOperation

Describes an operation or typically a HTTP method against a specific path.

描述一个http请求的操作:可指定httpMethod

@ApiParam

Adds additional meta-data for operation parameters.

字段说明:表示对参数的添加元数据,可指定是否必传 

@ApiResponse Describes a possible response of an operation.
@ApiResponses A wrapper to allow a list of multiple ApiResponse objects.
@Authorization Declares an authorization scheme to be used on a resource or an operation.
@AuthorizationScope Describes an OAuth2 authorization scope.
@ResponseHeader Represents a header that can be provided as part of the response.

The latest release also adds a number of annotations for adding extensions and metadata at the Swagger Definition level:

Name Description
@SwaggerDefinition Definition-level properties to be added to the generated Swagger definition
@Info General metadata for a Swagger definition
@Contact Properties to describe the contact person for a Swagger definition
@License Properties to describe the license for a Swagger definition
@Extension Adds an extension with contained properties
@ExtensionProperty Adds custom properties to an extension

示例1:

@Api(description = "日志相关")
@Controller
@RequestMapping("/log")
public class LogController {

	@Autowired
	private ILogDAO mapper;

	@ApiOperation(value = "查询记录(GET)", notes = "查询记录:http method is get", httpMethod = "GET", produces = MediaType.APPLICATION_JSON_VALUE)
	@RequestMapping(value = "/user/queryByGet.json",method = RequestMethod.GET)
	@ResponseBody
	public APIResponse> queryByGet(
			@ApiParam(required = true, hidden = false, value = "用户名") @PathVariable String name,
			@ApiParam(required = true, hidden = false, value = "删除标识",example = "true",allowableValues = "true|false") @PathVariable boolean flag,
			@ApiParam(required = true, value = "当前页",allowableValues = "1,100",example = "5") @RequestParam("currentPage") int currentPage,
			@ApiParam(required = true, value = "每页显示数量") @RequestParam("pageSize") int pageSize) {
		Page page = new Page();
		page.setLow((currentPage - 1) * pageSize);
		page.setHight(currentPage * pageSize);
		page.setUsername(name);
		List logs = mapper.selectUserLogByPage(page);

		return APIResponse.returnSuccess(logs);
	}

	@ApiOperation(value = "查询记录(POST)", notes = "查询记录:http method is post", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
	@RequestMapping(value = "/user/queryByPost.json",method = RequestMethod.POST)
	@ResponseBody
	public APIResponse> queryByPost(
			@ApiParam(required = true, hidden = false, value = "用户名") @PathVariable String name,
			@ApiParam(required = true, hidden = false, value = "删除标识",example = "true",allowableValues = "true|false") @PathVariable boolean flag,
			@ApiParam(required = true, value = "当前页",allowableValues = "1,5",example = "5") @RequestParam("currentPage") int currentPage,
			@ApiParam(required = true, value = "每页显示数量") @RequestParam("pageSize") int pageSize) {
		Page page = new Page();
		page.setLow((currentPage - 1) * pageSize);
		page.setHight(currentPage * pageSize);
		page.setUsername(name);
		List logs = mapper.selectUserLogByPage(page);

		return APIResponse.returnSuccess(logs);
	}
}

示例2:

@Api(description = "用户信息2")
@Controller("userController2")
@RequestMapping("/user2")
public class UserController2 {

    @Resource
    private IUserDAO iUserDAO;

    @Resource
    private ILogDAO iLogDAO;

    private Logger logger = LoggerFactory.getLogger(UserController2.class);

    @ApiOperation(value = "查询用户(GET)", notes = "查询用户详细信息", httpMethod = "GET", produces = MediaType.APPLICATION_JSON_VALUE)
    @RequestMapping(value = "/user/queryByGet.json", params = "name", method = RequestMethod.GET)
    @ResponseBody
    public APIResponse queryByGet(
            @RequestParam(required = true) String name) {
        System.out.println("param name:" + name);
        User user = null;
        try {
            user = iUserDAO.selectUser(name);
            return APIResponse.returnSuccess(user);
        } catch (Exception e) {
            logger.info("查询用户失败", e);
            e.printStackTrace();
            return APIResponse.returnFail("查询用户失败");
        }
    }

    @ApiOperation(value = "添加用户(POST)", notes = "添加用户详细信息", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    @RequestMapping(value = "/addByPost", method = RequestMethod.POST)
    @ResponseBody
    public APIResponse addByPost(
            @RequestBody User user,
            HttpServletResponse response) {
        try {
            iUserDAO.addUser(user);
            // 记录日志
            Log logger = new Log();
            logger.setUserId(user.getId());
            logger.setType(LogTypeEnum.create_user);
            logger.setContent("create user:" + user.getName());
            logger.setCreatetime(new Date());
            iLogDAO.insertLog(logger);

            return APIResponse.returnSuccess(user.getId());
        } catch (Exception e) {
            e.printStackTrace();
            logger.info("添加用户失败", e);
            return APIResponse.returnFail("添加用户失败");
        }
    }
}

User传入或返回参数说明样例:

@ApiModel(value = "userInfo", description = "用户信息")
public class User {
    @ApiModelProperty(value = "id", required = true, example = "1000", allowableValues = "1,100")
    private int id;
    @ApiModelProperty(value = "用户名", required = true, example = "张三")
    private String name;
    @ApiModelProperty(value = "生日", required = true, example = "日期")
    private Date birth;
    @ApiModelProperty(value = "用户状态", required = true, example = "0", allowableValues = "0,2")
    private UserStatusEnum status;
    @ApiModelProperty(value = "用户状态", required = false, example = "true", allowableValues = "true|false")
    private boolean testFlag2;


    @ApiModelProperty(value = "用户状态", hidden = true)
    private int flag = 0;

    public int getId() {
        return id;
    }

    @Override
    public String toString() {
        return "User [id=" + id + ", name=" + name + ", birth=" + birth
                + ", status=" + status + "]";
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @JsonSerialize(using = JsonDateSerializer.class)
    public Date getBirth() {
        return birth;
    }

    @JsonDeserialize(using = JsonDateDeserializer.class)
    public void setBirth(Date birth) {
        this.birth = birth;
    }

    public UserStatusEnum getStatus() {
        return status;
    }

    public void setStatus(UserStatusEnum status) {
        this.status = status;
    }

    public int getFlag() {
        return flag;
    }

    public void setFlag(int flag) {
        this.flag = flag;
    }

    public boolean isTestFlag2() {
        return testFlag2;
    }

    public void setTestFlag2(boolean testFlag2) {
        this.testFlag2 = testFlag2;
    }
}


5、通过以上配置启动项目在浏览器中访问下面地址

localhost:8080/swagger-ui.html

SpringMvc 3分钟集成swagger2_第1张图片

里面的详细描述如下

 

SpringMvc 3分钟集成swagger2_第2张图片

 

附:样例下载地址如下

https://gitee.com/liuyaohua/spring-simple/tree/master/swagger

参考:

1 https://github.com/swagger-api/swagger-core/wiki/Annotations-1.5.X#quick-annotation-overview

 

本文已同步更新到公众号,沟通交流请关注公众号。

SpringMvc 3分钟集成swagger2_第3张图片

你可能感兴趣的:(Java,进阶)