pom.xml中 引入 Swagger2 依赖
<!--swagger2--> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>${swagger2.version}</version> </dependency> <dependency> <groupId>com.google.guava</groupId> <artifactId>guava</artifactId> <version>19.0</version> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>${swagger2.version}</version> </dependency>
Application.java启动类中加上 @EnableSwagger2
@SpringBootApplication @EnableDiscoveryClient @Slf4j @MapperScan(basePackages = {"cn.mapper"}) @EnableSwagger2 public class Application { public static void main(String[] args) throws Exception { SpringApplication.run(Application.class, args); } }
创建一个 Swagger2 配置类
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.bind.annotation.RestController; import springfox.documentation.builders.ApiInfoBuilder; import springfox.documentation.builders.PathSelectors; import springfox.documentation.builders.RequestHandlerSelectors; import springfox.documentation.service.ApiInfo; import springfox.documentation.service.Contact; import springfox.documentation.spi.DocumentationType; import springfox.documentation.spring.web.plugins.Docket; import springfox.documentation.swagger2.annotations.EnableSwagger2; /** * @Description SwaggerAPI配置 */ @Configuration @EnableSwagger2 public class Swagger2 { @Bean public Docket createRestApi() { return new Docket(DocumentationType.SWAGGER_2) .enable(true) .apiInfo(apiInfo()) .select() .apis(RequestHandlerSelectors.withClassAnnotation(RestController.class)) .paths(PathSelectors.any()) .build(); } /** * 构建 api文档的详细信息函数 * @return */ private ApiInfo apiInfo() { return new ApiInfoBuilder() .title("接口API") .contact(new Contact("xiaowugui", "未定","xiaowugui.com")) .version("1.0.0") .build(); } }
创建一个用户注册接口
@RestController @RequestMapping("/user") @Api(tags = "用户服务") public class UserController { @Autowired UserServiceApi userServiceApi; @PostMapping("/register") public JsonResponse register(@RequestBody RegisterReq req,HttpServletRequest request){ String userAgent = request.getHeader("User-Agent"); req.setDevice(getDevice(userAgent)); String ip = request.getRemoteAddr(); req.setIp(ip); return userServiceApi.register(req); } }
声明接口参数对象: RegisterReq
@ApiModel 参数对象说明
@ApiModelProperty 参数属性说明
@Data @ApiModel @Validated public class RegisterReq extends BaseReq { @ApiModelProperty(value = "手机号") @NotBlank(message = "手机号不能为空") @Pattern(regexp = "^(((13[0-9])|(14[579])|(15([0-3]|[5-9]))|(16[6])|(17[0135678])|(18[0-9])|(19[89]))\d{8})$", message = "手机号格式错误") private String phone; @Size(min = 6,max = 20,message = "长度应该在6-20位之间") @Pattern(regexp="^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,20}$", message = "密码格式应该有数字和字母组成!") @ApiModelProperty(value = "密码") @NotBlank(message = "密码不能为空") private String password; }
启动项目:访问
http://localhost:8028/swagger-ui.html
就有接口的相关说明