一、依赖
<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>
二、Swagger配置类
package com.example.demo.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; 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; /** * @author wyw * @Description TODO * 接口文档处理类 * @date 2019/4/2 15:32 */ @Configuration //用@Configuration注解该类,等价于xml中配置beans;用@Bean标注方法等价于XML中配置bean public class Swagger2 { /** * * 功能描述: * 创建API应用 * appinfo()增加API相关信息 * 通过select()函数返回一个ApiSelectorBuilder实例,用来控制哪些接口暴露给Swagger来展示 * 指定扫描包路径来定义指定要建立API的目录 * @param: * @return: * @auther: wyw * @date: 2019/4/2 16:07 */ @Bean public Docket createRestApi(){ return new Docket(DocumentationType.SWAGGER_2) .groupName("Swagger使用demo") //设置栏目名 .apiInfo(apiInfo()) .select() //初始化并返回一个API选择构造器 .apis(RequestHandlerSelectors.basePackage("com.example.demo.controller")) .paths(PathSelectors.any()) //设置路径筛选 .build(); //构建 } /** * * 功能描述: * 创建API的基本信息(这些信息会展示在文东页面中) * 访问地址: http://项目实际地址/swagger-ui.html 例如:http://localhost:8080/swagger-ui.html * @param: * @return: * @auther: wyw * @date: 2019/4/2 16:10 */ private ApiInfo apiInfo(){ return new ApiInfoBuilder() .title("springboot利用swagger构建api文档") .contact(new Contact("wyw","http://ssish.com","wanyiwen@ssish.com")) .description("简单优雅的restful风格") //服务条款网址 //.termsOfServiceUrl("http://blog.csdn.net/forezp") .version("1.0") .build(); } }
用@Configuration注解该类,等价于XML中配置beans;用@Bean标注方法等价于XML中配置bean。
Application.class 加上注解@EnableSwagger2 表示开启Swagger
@SpringBootApplication @EnableSwagger2 //开启Swagger public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } }
三、Restful 接口
package com.example.demo.controller; import com.example.demo.bean.JsonResult; import com.example.demo.constant.ConstantStatus; import com.example.demo.entity.User; import com.example.demo.repository.UserRepository; import io.swagger.annotations.Api; import io.swagger.annotations.ApiImplicitParam; import io.swagger.annotations.ApiImplicitParams; import io.swagger.annotations.ApiOperation; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.*; import org.springframework.web.servlet.ModelAndView; import springfox.documentation.annotations.ApiIgnore; import java.util.*; /** * @author 万义文 * @Description TODO * @date 2018/12/22 13:10 */ @RestController @RequestMapping("/users") @Api(value = "UserController服务端接口文档", tags = "UserController服务端接口文档说明,包含用户的增删改查")//用在类上,说明该类的作用 访问swagger地址http://localhost:8081/swagger-ui.html public class UserController { /*@Api:用在类上,说明该类的作用。 @ApiOperation:注解来给API增加方法说明。 @ApiImplicitParams : 用在方法上包含一组参数说明。 @ApiImplicitParam:用来注解来给方法入参增加说明。 @ApiResponses:用于表示一组响应 @ApiResponse:用在@ApiResponses中,一般用于表达一个错误的响应信息 * code:数字,例如400 * message:信息,例如"请求参数没填好" * response:抛出异常的类 @ApiModel:描述一个Model的信息(一般用在请求参数无法使用@ApiImplicitParam注解进行描述的时候) * @ApiModelProperty:描述一个model的属性*/ //创建线程安全的Map static Map<Integer,User> users = Collections.synchronizedMap(new HashMap<Integer, User>()); @ApiOperation(value = "获取用户详细信息",notes = "根据url的id来获取用户详细信息") @ApiImplicitParams(@ApiImplicitParam(name = "id",value = "用户id",required = true,dataType = "Integer",paramType = "path")) @RequestMapping(value = "queryById/{id}" ,method = RequestMethod.GET) public ResponseEntity<JsonResult> getUserById(@PathVariable(value = "id") Integer id){ JsonResult r = new JsonResult(); try { User user = users.get(id); r.setResult(user); r.setStatus(ConstantStatus.REQUEST_STATUS_SUCCESS); } catch (Exception e) { r.setStatus(ConstantStatus.REQUEST_STATUS_ERROR); r.setResult(e.getMessage()); e.printStackTrace(); } return ResponseEntity.ok(r); } @ApiOperation(value="获取用户列表", notes="获取用户列表") @RequestMapping(value = "getusers", method = RequestMethod.GET) public ResponseEntity<JsonResult> getUserList(){ JsonResult r = new JsonResult(); try { List<User> userlist = new ArrayList<User>(users.values()); r.setResult(userlist); r.setStatus(ConstantStatus.REQUEST_STATUS_SUCCESS); } catch (Exception e) { r.setResult(e.getMessage()); r.setResult(ConstantStatus.REQUEST_STATUS_ERROR); e.printStackTrace(); } return ResponseEntity.ok(r); } @ApiOperation(value="创建用户", notes="根据User对象创建用户") @ApiImplicitParam(name = "user", value = "用户详细实体user", required = true, dataType = "User") @RequestMapping(value = "adduser", method = RequestMethod.POST) public ResponseEntity<JsonResult> add (@RequestBody User user){ JsonResult r = new JsonResult(); try { users.put(user.getId(), user); r.setResult(user.getId()); r.setStatus(ConstantStatus.REQUEST_STATUS_SUCCESS); } catch (Exception e) { r.setResult(e.getClass().getName() + ":" + e.getMessage()); r.setStatus(ConstantStatus.REQUEST_STATUS_ERROR); e.printStackTrace(); } return ResponseEntity.ok(r); } @ApiOperation(value="删除用户", notes="根据url的id来指定删除用户") @ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "Long", paramType = "path") @RequestMapping(value = "deleteuser/{id}", method = RequestMethod.DELETE) public ResponseEntity<JsonResult> delete (@PathVariable(value = "id") Integer id){ JsonResult r = new JsonResult(); try { users.remove(id); r.setResult(id); r.setStatus(ConstantStatus.REQUEST_STATUS_SUCCESS); } catch (Exception e) { r.setResult(e.getClass().getName() + ":" + e.getMessage()); r.setStatus(ConstantStatus.REQUEST_STATUS_ERROR); e.printStackTrace(); } return ResponseEntity.ok(r); } @ApiOperation(value="更新信息", notes="根据url的id来指定更新用户信息") @ApiImplicitParams({ @ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "Long",paramType = "path"), @ApiImplicitParam(name = "user", value = "用户实体user", required = true, dataType = "User") }) @RequestMapping(value = "user/{id}", method = RequestMethod.PUT) public ResponseEntity<JsonResult> update (@PathVariable("id") Integer id, @RequestBody User user){ JsonResult r = new JsonResult(); try { User u = users.get(id); u.setUsername(user.getUsername()); u.setEmail(user.getEmail()); users.put(id, u); r.setResult(u); r.setStatus(ConstantStatus.REQUEST_STATUS_SUCCESS); } catch (Exception e) { r.setResult(e.getClass().getName() + ":" + e.getMessage()); r.setStatus(ConstantStatus.REQUEST_STATUS_ERROR); e.printStackTrace(); } return ResponseEntity.ok(r); } @ApiIgnore//使用该注解忽略这个API @RequestMapping(value = "/hi", method = RequestMethod.GET) public String jsonTest() { return " hi you!"; } }
Json格式输出类 JsonResult.class
package com.example.demo.bean; /** * @author wyw * @Description TODO * @date 2019/4/2 16:31 */ public class JsonResult { private String status ; private Object result ; public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public Object getResult() { return result; } public void setResult(Object result) { this.result = result; } }
实体User.class
public class User { private int id; private String username; private int age; private Date ctm; // Getter Setter }
启动SpringBoot项目,访问 http://localhost:8080/swagger-ui.html