先後臺分離的開發漸漸已成趨勢。那麼先後端的溝通就成了問題,包括移動端,web端。若是有一個東西在咱們寫完代碼的時候,自動將接口的全部註釋,調用文檔提供出來,是否是一件很美好的事情。那就是使用swagger.html
1.使用swagger,首先在pom中引入jar依賴。java
<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.Application.java中引入@EnableSwagger2來啓動swagger註解web
@Configuration @SpringBootApplication // 組件掃描 @EnableScheduling @EnableAsync @EnableSwagger2 public class Application {
3.使用接口註解spring
@RestController @RequestMapping("/user") @Api("userController相關api") public class UserController { @Autowired private UserService userService; // @Autowired // private MyRedisTemplate myRedisTemplate; @ApiOperation("獲取用戶信息") @ApiImplicitParams({ @ApiImplicitParam(paramType="header",name="username",dataType="String",required=true,value="用戶的姓名",defaultValue="zhaojigang"), @ApiImplicitParam(paramType="query",name="password",dataType="String",required=true,value="用戶的密碼",defaultValue="wangna") }) @ApiResponses({ @ApiResponse(code=400,message="請求參數沒填好"), @ApiResponse(code=404,message="請求路徑沒有或頁面跳轉路徑不對") }) @RequestMapping(value="/getUser",method=RequestMethod.GET) public User getUser(@RequestHeader("username") String username, @RequestParam("password") String password) { return userService.getUser(username,password); } // @RequestMapping("/testJedisCluster") // public User testJedisCluster(@RequestParam("username") String username){ // String value = myRedisTemplate.get(MyConstants.USER_FORWARD_CACHE_PREFIX, username); // if(StringUtils.isBlank(value)){ // myRedisTemplate.set(MyConstants.USER_FORWARD_CACHE_PREFIX, username, JSON.toJSONString(getUser())); // return null; // } // return JSON.parseObject(value, User.class); // } }
說明:後端
4.啓動服務,瀏覽器輸入"http://localhost:8080/swagger-ui.html"api