728x90

pom.xml

<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-boot-starter</artifactId>
    <version>3.0.0</version>
<dependency>

메인 클래스에 @EnableOpenApi 추가

@EnableOpenApi
@SpringBootApplication
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }

}

샘플 Controller 작성 해보기 

@Api(tags="사용자관리")
@RestController
public class UserController {

    @ApiOperation("사용자생성")
    @PostMapping("/users")
    public User create(@RequestBody @Valid User user) {
        return user;
    }

    @ApiOperation("사용자상세")
    @GetMapping("/users/{id}")
    public User findById(@PathVariable Long id) {
        return new User("bbb", 21, "인천", "aaa@bbb.com");
    }

    @ApiOperation("사용자목록")
    @GetMapping("/users")
    public List<User> list(@ApiParam("조회페이지") @RequestParam int pageIndex,
                           @ApiParam("페이당건수") @RequestParam int pageSize) {
        List<User> result = new ArrayList<>();
        result.add(new User("aaa", 50, "서울", "aaa@ccc.com"));
        result.add(new User("bbb", 21, "인천", "aaa@ddd.com"));
        return result;
    }

    @ApiIgnore
    @DeleteMapping("/users/{id}")
    public String deleteById(@PathVariable Long id) {
        return "delete user : " + id;
    }

}

@Data
@NoArgsConstructor
@AllArgsConstructor
@ApiModel("사용자기본정보")
public class User {

    @ApiModelProperty("이름")
    @Size(max = 20)
    private String name;
    @ApiModelProperty("나이")
    @Max(150)
    @Min(1)
    private Integer age;
    @NotNull
    private String address;
    @Pattern(regexp = "^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\\.[a-zA-Z0-9_-]+)+$")
    private String email;

}

http://localhost:8080/swagger-ui/index.html 접속후 확인!

끝!

728x90
Spring Boot 1.x 에서는 해당 RequestMappingHandlerAdapter 로그가 자세하게 찍혔지만 Spring Boot 2.x 부터는 별도로 설정을 해줘야 한다.

Spring Boot 1.x 당시 로그

2020-02-11 15:32:39.293  INFO 48395 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2020-02-11 15:32:39.482  INFO 48395 --- [           main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for @ControllerAdvice: org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext@7ff95560: startup date [Tue Feb 11 15:32:37 CST 2020]; root of context hierarchy
2020-02-11 15:32:39.568  INFO 48395 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/users/{id}],methods=[GET]}" onto public com.didispace.chapter26.User com.didispace.chapter26.UserController.getUser(java.lang.Long)
2020-02-11 15:32:39.569  INFO 48395 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/users/{id}],methods=[PUT]}" onto public java.lang.String com.didispace.chapter26.UserController.putUser(java.lang.Long,com.didispace.chapter26.User)
2020-02-11 15:32:39.570  INFO 48395 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/users/],methods=[GET]}" onto public java.util.List<com.didispace.chapter26.User> com.didispace.chapter26.UserController.getUserList()
2020-02-11 15:32:39.570  INFO 48395 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/users/],methods=[POST]}" onto public java.lang.String com.didispace.chapter26.UserController.postUser(com.didispace.chapter26.User)
2020-02-11 15:32:39.570  INFO 48395 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/users/{id}],methods=[DELETE]}" onto public java.lang.String com.didispace.chapter26.UserController.deleteUser(java.lang.Long)
2020-02-11 15:32:39.573  INFO 48395 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error]}" onto public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController.error(javax.servlet.http.HttpServletRequest)
2020-02-11 15:32:39.573  INFO 48395 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error],produces=[text/html]}" onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)
2020-02-11 15:32:39.590  INFO 48395 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2020-02-11 15:32:39.590  INFO 48395 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
Spring Boot 2.x 에서 바뀐 로그 형태
2022-12-21 15:34:15.280  INFO 48784 --- [main] c.d.chapter26.Chapter26Application       : Starting Chapter26Application on zhaiyongchaodeMacBook-Pro.local with PID 48784 (/Users/zhaiyongchao/Documents/git/github/SpringBoot-Learning/2.1.x/chapter2-6/target/classes started by zhaiyongchao in /Users/zhaiyongchao/Documents/git/github/SpringBoot-Learning/2.1.x)
2022-12-21 15:34:15.283  INFO 48784 --- [main] c.d.chapter26.Chapter26Application       : No active profile set, falling back to default profiles: default
2022-12-21 15:34:16.556  INFO 48784 --- [main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8080 (http)
2022-12-21 15:34:16.587  INFO 48784 --- [main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2022-12-21 15:34:16.588  INFO 48784 --- [main] org.apache.catalina.core.StandardEngine  : Starting Servlet engine: [Apache Tomcat/9.0.16]
2022-12-21 15:34:16.596  INFO 48784 --- [main] o.a.catalina.core.AprLifecycleListener   : The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: [/Users/zhaiyongchao/Library/Java/Extensions:/Library/Java/Extensions:/Network/Library/Java/Extensions:/System/Library/Java/Extensions:/usr/lib/java:.]
2022-12-21 15:34:16.702  INFO 48784 --- [main] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2022-12-21 15:34:16.702  INFO 48784 --- [main] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 1377 ms
2022-12-21 15:34:16.954  INFO 48784 --- [main] o.s.s.concurrent.ThreadPoolTaskExecutor  : Initializing ExecutorService 'applicationTaskExecutor'
2022-12-21 15:34:17.187  INFO 48784 --- [main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8080 (http) with context path ''
2022-12-21 15:34:17.192  INFO 48784 --- [main] c.d.chapter26.Chapter26Application       : Started Chapter26Application in 2.238 seconds (JVM running for 2.764)

application.properties 파일에 아래 값을 추가 

logging.level.org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping=trace

아래와 같이 로그 출력 내용이 변경되었다.

2022-12-21 15:36:09.787 TRACE 49215 --- [main] s.w.s.m.m.a.RequestMappingHandlerMapping : 
	c.d.c.UserController:
	{PUT /users/{id}}: putUser(Long,User)
	{GET /users/{id}}: getUser(Long)
	{POST /users/}: postUser(User)
	{GET /users/}: getUserList()
	{DELETE /users/{id}}: deleteUser(Long)
2022-12-21 15:36:09.791 TRACE 49215 --- [main] s.w.s.m.m.a.RequestMappingHandlerMapping : 
	o.s.b.a.w.s.e.BasicErrorController:
	{ /error}: error(HttpServletRequest)
	{ /error, produces [text/html]}: errorHtml(HttpServletRequest,HttpServletResponse)
2022-12-21 15:36:09.793 DEBUG 49215 --- [main] s.w.s.m.m.a.RequestMappingHandlerMapping : 7 mappings in 'requestMappingHandlerMapping'

끝!

728x90

기본분류

@RestController
@RequestMapping(value = "/teacher")
static class TeacherController {

    @GetMapping("/xxx")
    public String xxx() {
        return "xxx";
    }
}

@RestController
@RequestMapping(value = "/student")
static class StudentController {

    @ApiOperation("학생리스트")
    @GetMapping("/list")
    public String bbb() {
        return "bbb";
    }

    @ApiOperation("특정학생의 담임목록")
    @GetMapping("/his-teachers")
    public String ccc() {
        return "ccc";
    }

    @ApiOperation("학생생성")
    @PostMapping("/aaa")
    public String aaa() {
        return "aaa";
    }
}

TAG 분류

@Api(tags = "담임관리")
@RestController
@RequestMapping(value = "/teacher")
static class TeacherController {

    // ...

}

@Api(tags = "학생관리")
@RestController
@RequestMapping(value = "/student")
static class StudentController {

    // ...

}

@tag 내부 코드를 들여다 보면

때문에 아래와 같이 적용 가능하다.

@Api(tags = {"담임관리", "인사관리"})
@RestController
@RequestMapping(value = "/teacher")
static class TeacherController {

    // ...

}

@Api(tags = {"학생관리", "인사관리"})
@RestController
@RequestMapping(value = "/student")
static class StudentController {

    // ...

}

좀 더 세분화 하여 분류할수 있다.

@Api(tags = {"담임관리","인사관리"})
@RestController
@RequestMapping(value = "/teacher")
static class TeacherController {

    @ApiOperation(value = "xxx")
    @GetMapping("/xxx")
    public String xxx() {
        return "xxx";
    }
}

@Api(tags = {"학생관리"})
@RestController
@RequestMapping(value = "/student")
static class StudentController {

    @ApiOperation(value = "학생목록", tags = "인사목록")
    @GetMapping("/list")
    public String bbb() {
        return "bbb";
    }

    @ApiOperation("특정학생의 담임목록")
    @GetMapping("/his-teachers")
    public String ccc() {
        return "ccc";
    }

    @ApiOperation("학생생성")
    @PostMapping("/aaa")
    public String aaa() {
        return "aaa";
    }
}

분류된 그룹들을 순서 지정하기

또는 설정파일 변경

swagger.ui-config.tags-sorter=alpha

실제 코드를 보면

public enum TagsSorter {
  ALPHA("alpha");

  private final String value;

  TagsSorter(String value) {
    this.value = value;
  }

  @JsonValue
  public String getValue() {
    return value;
  }

  public static TagsSorter of(String name) {
    for (TagsSorter tagsSorter : TagsSorter.values()) {
      if (tagsSorter.value.equals(name)) {
        return tagsSorter;
      }
    }
    return null;
  }
}

코드에서 확인된 바로는 영어문자 즉 api 그룹의 영문이름을 기준으로 순서를 지정한다. 그러면 여기서 꼼수를 부리면 앞에 수자를 넣어서 하면 순서가 지정된다.

@Api(tags = {"1-담임관리", "3-인사관리"})
@RestController
@RequestMapping(value = "/teacher")
static class TeacherController {

    // ...

}

@Api(tags = {"학생관리"})
@RestController
@RequestMapping(value = "/student")
static class StudentController {

    @ApiOperation(value = "학생목록", tags = "3-인사관리")
    @GetMapping("/list")
    public String bbb() {
        return "bbb";
    }

    // ...

}

API 자체에 대한 정렬

swagger.ui-config.operations-sorter=alpha

API parameter 를 정렬하기

@Data
@ApiModel(description="User Model")
public class User {

    @ApiModelProperty("user 식별자", position = 1)
    private Long id;

    @NotNull
    @Size(min = 2, max = 10)
    @ApiModelProperty("user 이름", position = 2)
    private String name;

    @NotNull
    @Max(100)
    @Min(18)
    @ApiModelProperty("user 나이", position = 3)
    private Integer age;

    @NotNull
    @Email
    @ApiModelProperty("user 메일", position = 4)
    private String email;

}

끝!

728x90

Bean Validation 1.0 은 JSR-303이고 Bean Validation 2.0 은 JSR-380이다.

우리는 특정 값이 null 을 허용하지 않고 싶다. 그러면 아래와 같이 @notnull 하나 추가하면 바로 해결된다.
@Data
@ApiModel(description="User Model")
public class User {

    @ApiModelProperty("user 식별자")
    private Long id;

    @NotNull
    @ApiModelProperty("user 이름")
    private String name;

    @NotNull
    @ApiModelProperty("user 나이")
    private Integer age;

}

 

체크해야 되는 부분에서 @Valid 어노테이션을 달아준다.
@PostMapping("/")
@ApiOperation(value = "사용자 생성", notes = "user model 세팅된 값으로 사용자 생성")
public String postUser(@Valid @RequestBody User user) {
    users.put(user.getId(), user);
    return "success";
}

cUrl 요청해본다.

curl -X POST \
  http://localhost:8080/users/ \
  -H 'Content-Type: application/json' \
  -H 'Postman-Token: 72745d04-caa5-44a1-be84-ba9c115f4dfb' \
  -H 'cache-control: no-cache' \
  -d '{
}'

결과는 ???

{
    "timestamp": "2022-12-21T05:45:19.221+0000",
    "status": 400,
    "error": "Bad Request",
    "errors": [
        {
            "codes": [
                "NotNull.user.age",
                "NotNull.age",
                "NotNull.java.lang.Integer",
                "NotNull"
            ],
            "arguments": [
                {
                    "codes": [
                        "user.age",
                        "age"
                    ],
                    "arguments": null,
                    "defaultMessage": "age",
                    "code": "age"
                }
            ],
            "defaultMessage": "null을 허용안함",
            "objectName": "user",
            "field": "age",
            "rejectedValue": null,
            "bindingFailure": false,
            "code": "NotNull"
        },
        {
            "codes": [
                "NotNull.user.name",
                "NotNull.name",
                "NotNull.java.lang.String",
                "NotNull"
            ],
            "arguments": [
                {
                    "codes": [
                        "user.name",
                        "name"
                    ],
                    "arguments": null,
                    "defaultMessage": "name",
                    "code": "name"
                }
            ],
            "defaultMessage": "null을 허용안함",
            "objectName": "user",
            "field": "name",
            "rejectedValue": null,
            "bindingFailure": false,
            "code": "NotNull"
        }
    ],
    "message": "Validation failed for object='user'. Error count: 2",
    "path": "/users/"
}
다른것도 체크해보자. 문자열 길이, 수자크기, 포맷 등.
@Data
@ApiModel(description="User Model")
public class User {

    @ApiModelProperty("user 식별자")
    private Long id;

    @NotNull
    @Size(min = 2, max = 10)
    @ApiModelProperty("user 이름")
    private String name;

    @NotNull
    @Max(100)
    @Min(18)
    @ApiModelProperty("user 나이")
    private Integer age;

    @NotNull
    @Email
    @ApiModelProperty("user 메일")
    private String email;

}

요청

curl -X POST \
  http://localhost:8080/users/ \
  -H 'Content-Type: application/json' \
  -H 'Postman-Token: 114db0f0-bdce-4ba5-baf6-01e5104a68a3' \
  -H 'cache-control: no-cache' \
  -d '{
    "name": "abcdefg",
    "age": 17,
    "email": "aaaa"
}'

응답

{
    "timestamp": "2022-12-21T06:24:30.518+0000",
    "status": 400,
    "error": "Bad Request",
    "errors": [
        {
            "codes": [
                "Size.user.name",
                "Size.name",
                "Size.java.lang.String",
                "Size"
            ],
            "arguments": [
                {
                    "codes": [
                        "user.name",
                        "name"
                    ],
                    "arguments": null,
                    "defaultMessage": "name",
                    "code": "name"
                },
                5,
                2
            ],
            "defaultMessage": "2와10사이",
            "objectName": "user",
            "field": "name",
            "rejectedValue": "abcdefg",
            "bindingFailure": false,
            "code": "Size"
        },
        {
            "codes": [
                "Min.user.age",
                "Min.age",
                "Min.java.lang.Integer",
                "Min"
            ],
            "arguments": [
                {
                    "codes": [
                        "user.age",
                        "age"
                    ],
                    "arguments": null,
                    "defaultMessage": "age",
                    "code": "age"
                },
                10
            ],
            "defaultMessage": "18보다 작을수 없습니다.",
            "objectName": "user",
            "field": "age",
            "rejectedValue": 8,
            "bindingFailure": false,
            "code": "Min"
        },
        {
            "codes": [
                "Email.user.email",
                "Email.email",
                "Email.java.lang.String",
                "Email"
            ],
            "arguments": [
                {
                    "codes": [
                        "user.email",
                        "email"
                    ],
                    "arguments": null,
                    "defaultMessage": "email",
                    "code": "email"
                },
                [],
                {
                    "defaultMessage": ".*",
                    "codes": [
                        ".*"
                    ],
                    "arguments": null
                }
            ],
            "defaultMessage": "메일격식이 아닙니다.",
            "objectName": "user",
            "field": "email",
            "rejectedValue": "aaaa",
            "bindingFailure": false,
            "code": "Email"
        }
    ],
    "message": "Validation failed for object='user'. Error count: 3",
    "path": "/users/"
}
이제 더 이상 parameter 하나씩 체크하기 위해서 if ...else  지옥에서 벗어나자.
 
끝!

+ Recent posts