1. 程式人生 > >springboot+Swagger2生成API

springboot+Swagger2生成API

  1. 配置pom.xml
<!-- swagger生成介面API -->
		<dependency>
			<groupId>io.springfox</groupId>
			<artifactId>springfox-swagger2</artifactId>
			<version>2.7.0</version>
		</dependency>

		<!-- 介面API生成html文件 -->
		<dependency>
			<groupId>io.springfox</groupId>
			<artifactId>springfox-swagger-ui</artifactId>
			<version>2.6.1</version>
		</dependency>
  1. Swagger2配置類
//和Application在一個包
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;

@Configuration
@EnableSwagger2
public class Swagger2 {

	@Bean
	public Docket createRestApi() {
		return new Docket(DocumentationType.SWAGGER_2)
				.apiInfo(apiInfo())
				.select()
				.apis(RequestHandlerSelectors.basePackage("com.yjy.user"))
				.paths(PathSelectors.any())
				.build();
	}

	private ApiInfo apiInfo() {
		return new ApiInfoBuilder()
				.title("使用者管理RESTful APIs")
				.description("請關注:http://XXXX.com/")
				.termsOfServiceUrl("http://xxxx.com/")
				.version("1.0")
				.build();
	}

}
  1. 下載Swagger UI
    路徑https://github.com/swagger-api/swagger-ui
    把dist檔案複製到static下面,重名為api,修改index.html其中
    url: “http://localhost:9090/v2/api-docs”,
    訪問路徑為http://localhost:9090/api/index.html
  2. Controller配置
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.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;

@RestController
@RequestMapping("/user")
@Api(tags="使用者相關API")
public class UserController extends BaseController{
    @Autowired
    private UserService userService;
    @Autowired
    private TokenService tokenService;

    @ApiOperation(value="獲取所有使用者列表")
    @PreAuthorize("hasRole('ADMIN')")
    @RequestMapping(value = "/getAllUsers",method = RequestMethod.GET)
    public Object getAllUsers(){
        return new ResponseData(ExceptionMsg.SUCCESS,userService.getAllUsers());
    }

    @ApiOperation(value="建立使用者", notes="根據User物件建立使用者,其中username、password、active為必填項")
    @ApiImplicitParam(name = "user", value = "使用者實體user", required = true, dataType = "User")
    @RequestMapping(value = "/addUser",method = RequestMethod.POST)
    public Object addUser(@RequestBody  User user) throws IOException{
        return tokenService.register(user);
    }
    @ApiOperation(value="更新使用者詳細資訊", notes="根據傳過來的user資訊來更新使用者詳細資訊,username為唯一鍵")
    @ApiImplicitParam(name = "updateUser", value = "使用者實體", required = true, dataType = "User")
    @RequestMapping(value = "/updateUser",method = RequestMethod.PUT)
    public Object updateUser(@RequestBody User updateUser) throws IOException{
        int i = userService.updateUser(updateUser);
        if(i == Constants.NO_EXIST){
            return Response.result(ExceptionMsg.NO_EXIST);
        }else{
            return Response.result(ExceptionMsg.SUCCESS);
        }
    }
    @ApiOperation(value="刪除使用者", notes="根據使用者名稱來指定刪除物件")
    @ApiImplicitParam(name = "username", value = "使用者名稱", required = true, dataType = "String",paramType="query")
    @ApiResponses({ @ApiResponse(code = Constants.SUCCESS, message = "操作成功"),
            @ApiResponse(code = Constants.NO_EXIST, message = "記錄不存在"),
            @ApiResponse(code = Constants.NO_AUTH, message = "無許可權")})
    @RequestMapping(value = "/deleteUser",method = RequestMethod.DELETE)
    public Object deleteUser(@RequestParam String username){
        int i = userService.deleteUser(username);
        if(i == Constants.NO_EXIST){
            return Response.result(ExceptionMsg.NO_EXIST);
        }else{
            return Response.result(ExceptionMsg.SUCCESS);
        }
    }
    @ApiOperation(value="獲取使用者詳細資訊", notes="通過username來獲取使用者詳細資訊")
    @ApiImplicitParam(name = "username", value = "使用者名稱", required = true, dataType = "String",paramType="query")
    @RequestMapping(value = "/findUser",method = RequestMethod.GET)
    public Object findUser(@RequestParam(value="username")String username){
        return new ResponseData(ExceptionMsg.SUCCESS,userService.findUser(username));
    }
    @ApiOperation(value="模糊查詢使用者資訊")
    @ApiImplicitParams(
            {@ApiImplicitParam(name = "field", value = "屬性名", required = true, dataType = "String", paramType = "query"),
                    @ApiImplicitParam(name = "word", value = "搜尋的單詞", required = true, dataType = "String", paramType = "query")})
    @RequestMapping(value = "/findUsersByLike",method = RequestMethod.GET)
    public Object findUsersByLike(@RequestParam(value="field")String field, @RequestParam(value="word")String word){
        return new ResponseData(ExceptionMsg.SUCCESS,userService.findUsersByLike(field,word));
    }
    @ApiOperation(value="通過角色獲取使用者資訊", notes="通過roleName來獲取使用者資訊")
    @ApiImplicitParam(name = "roleName", value = "角色名", required = true, dataType = "String",paramType="query")
    @RequestMapping(value = "/findUsersByRoleName",method = RequestMethod.GET)
    public Object findUsersByRoleName(@RequestParam(value="roleName")String roleName){
        return new ResponseData(ExceptionMsg.SUCCESS,userService.findUsersByRoleName(roleName));
    }
    @ApiOperation(value="獲取使用者所有許可權", notes="通過username來獲取使用者所有許可權")
    @ApiImplicitParam(name = "username", value = "使用者名稱", required = true, dataType = "String",paramType="query")
    @RequestMapping(value = "/findAllAuths",method = RequestMethod.GET)
    public Object findAllAuths(@RequestParam(value="username")String username){
        return new ResponseData(ExceptionMsg.SUCCESS,userService.findAllAuths(username));
    }
    @ApiOperation(value="通過使用者組獲取使用者", notes="通過userGroupName來獲取使用者")
    @ApiImplicitParam(name = "userGroupName", value = "使用者組名", required = true, dataType = "String",paramType="query")
    //@ApiIgnore //使用這個註解忽略這個介面
    @RequestMapping(value = "/findUsersByUserGroupName",method = RequestMethod.GET)
    public Object findUsersByUserGroupName(@RequestParam(value="userGroupName")String userGroupName) {
        return new ResponseData(ExceptionMsg.SUCCESS,userService.findUsersByUserGroupName(userGroupName));
    }

}