SpringBoot(十四)-- 整合Swagger2
1.pom依赖
<dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.2.2</version> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>2.2.2</version> </dependency>
2.Swagger配置类
增加@EnableSwagger2和@Configuration注解
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.spi.DocumentationType; import springfox.documentation.spring.web.plugins.Docket; import springfox.documentation.swagger2.annotations.EnableSwagger2; /** * ClassName:SwaggerConfig * Date: 2017年12月5日 上午11:54:54 * @author xbq * @version * @since JDK 1.8 */ @Configuration @EnableSwagger2 public class SwaggerConfig { @Bean public Docket createRestApi() { return new Docket(DocumentationType.SWAGGER_2) .apiInfo(apiInfo()) .select() .apis(RequestHandlerSelectors.basePackage("com.rxwx.controller")) .paths(PathSelectors.any()) .build(); } private ApiInfo apiInfo() { return new ApiInfoBuilder() .title("springboot利用swagger构建api文档") .description("简单优雅的restfun风格,http://www.cnblogs.com/xbq8080") .termsOfServiceUrl("http://www.cnblogs.com/xbq8080") .contact("小葱拌豆腐~") .version("1.0") .build(); } }
通过@Configuration注解,让Spring来加载该类配置,@EnableSwagger2注解来启用Swagger2。
再通过createRestApi函数创建Docket的Bean之后,apiInfo()用来创建该Api的基本信息(这些基本信息会展现在文档页面中)。select()函数返回一个ApiSelectorBuilder实例用来控制哪些接口暴露给Swagger来展现,本例采用指定扫描的包路径来定义,Swagger会扫描该包下所有Controller定义的API,并产生文档内容(除了被@ApiIgnore注解的API)。
3.启动类加上注解
@EnableSwagger2
4.在控制层 增加 注解
例如:
/** * 用户控制器 */ @RestController @RequestMapping(value = "/user") @Api("用户信息相关api") public class UserController { @Autowired UserService userService; /** * register:(注册). * @param nickName * @param password * @param phone * @return */ @ApiOperation(value="用户注册", notes="用户注册") @ApiImplicitParams({ @ApiImplicitParam(paramType="query", name="nickName", dataType="String", required=true, value="用户的姓名"), @ApiImplicitParam(paramType="query", name="password", dataType="String", required=true, value="用户的密码"), @ApiImplicitParam(paramType="query", name="phone", dataType="String", required=true, value="用户的电话") }) @RequestMapping(value = "/register", method = RequestMethod.GET) public Object register( String nickName, String password, String phone) { if(StringUtils.isEmpty(nickName)){ return Result.error("-100","nickName为空"); } if(StringUtils.isEmpty(password)){ return Result.error("-100","password为空"); } if(StringUtils.isEmpty(nickName)){ return Result.error("-100","phone为空"); } User user = new User(); user.setNickName(nickName); user.setPassword(MD5Util.generateMD5(password)); user.setPhone(phone); try { userService.insert(user); } catch (Exception e) { logger.error(e.getMessage(),e); return Result.error("-100","注册错误"); } return Result.success("success"); } /** * login:(登录). * @author xbq * Date:2017年11月23日下午6:00:09 * * @param nickName * @param password * @return */ @ApiOperation(value="用户登录", notes="用户登录") @ApiImplicitParams({ @ApiImplicitParam(paramType="query", name="nickName", dataType="String", required=true, value="用户的姓名"), @ApiImplicitParam(paramType="query", name="password", dataType="String", required=true, value="用户的密码") }) @RequestMapping(value = "/login", method = RequestMethod.GET) public Object login(String nickName , String password) { if(StringUtils.isEmpty(nickName)){ return Result.error("-100","nickName为空"); } if(StringUtils.isEmpty(password)){ return Result.error("-100","password为空"); } // 根据用户名查询密码 User userResult = null; try { userResult = userService.findUserByIdOrName(null, nickName); } catch (Exception e1) { logger.error(e1.getMessage(),e1); return Result.error("-100","根据用户名查询用户密码错误"); } if(userResult == null) { return Result.error("-100","不存在该用户名"); } // 将数据库中的密码 和 界面传来的密码进行验证 boolean flag = MD5Util.verify(password, userResult.getPassword()); if(!flag) { return Result.error("-100","密码错误"); } User user = null; try { User userParam = new User(); userParam.setNickName(nickName); user = userService.findUser(userParam); } catch (Exception e) { logger.error(e.getMessage(),e); return Result.error("-100","根据用户名查询用户错误"); } if(user == null) { return Result.error("-100","用户名或密码错误"); } // 生成token String token = System.currentTimeMillis() + ""; user.setToken(token); return Result.success(user); } /** * account:(查询账户信息). * @author xbq * Date:2017年11月23日下午6:00:18 * * @param id * @return */ @ApiOperation(value="获取指定id用户的详细信息", notes="根据user的id来获取用户详细信息") @ApiImplicitParam(paramType="query", name="id", dataType="Integer", required=true, value="用户id") @RequestMapping(value = "/account", method = RequestMethod.GET) public Object account(Integer id){ User user = null; try { user = userService.findUserByIdOrName(id ,null); } catch (Exception e) { e.printStackTrace(); } UserDetail target = new UserDetail(); org.springframework.beans.BeanUtils.copyProperties(user, target); return Result.success(target); } }
完成上述代码后,打包Spring Boot程序并启动,打开浏览器访问:http://localhost:8080/swagger-ui.html,就能看到前文所展示的RESTful API的页面。