[Spring Boot] User Entity

이준영·2024년 11월 11일

Spring MSA 프로젝트

목록 보기
2/15
post-thumbnail

1. 의존성 추가


implementation 'org.springframework.boot:spring-boot-starter-validation'
implementation 'org.springframework.boot:spring-boot-starter-security'

compileOnly 'org.projectlombok:lombok:1.18.24'
annotationProcessor 'org.projectlombok:lombok:1.18.24'
  • API 유효성 검증을 위해 validation을 추가하였다.
  • 사용자 패스워드 암호화와 추후 security를 통한 인증/인가 설정을 위해 spring security를 추가하였다.
  • 편의를 위해 Lombok을 추가하였다.

2. User Entity

@Entity
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class UserEntity {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String username;
    private String password;

    private String role;
    private String type;

    private String name;
    private String email;
    private String phone;

    @CreationTimestamp
    private LocalDateTime createdAt;

    @UpdateTimestamp
    private LocalDateTime updatedAt;

}
  • JPA 활용과 Lombok 어노테이션 등 필요 어노테이션을 추가해주었다.

3. Response

@Getter
@RequiredArgsConstructor
public enum ResponseCode {

    SUCCESS("성공", 0),
    FAIL("실패", -1);

    private final String message;
    private final int code;

}
@Getter
public final class MessageResponse<D> {
    final private int code;
    final private String message;
    final private D data;

    private MessageResponse(int code, String message, D data) {
        this.code = code;
        this.message = message;
        this.data = data;
    }

    public static <D> MessageResponse<?> of(ResponseCode responseCode, D data) {
        return new MessageResponse<>(responseCode.getCode() , responseCode.getMessage(), data);
    }

    public static <D> MessageResponse<?> of(ResponseCode responseCode) {
        return new MessageResponse<>(responseCode.getCode() , responseCode.getMessage(), null);
    }
}
  • 응답 규격 통일성을 위해 Response Code와 Response DTO를 추가하였다.
  • 실패 코드에 대해선 추후 세분화 진행 해야겠다.
@RestControllerAdvice
public class GeneralExceptionHandler {

    // 파라미터 유효성 검증 에러
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseEntity<?> handleValidationExceptions(MethodArgumentNotValidException e) {
        return ResponseEntity.badRequest().body(
                MessageResponse.of(ResponseCode.FAIL));
    }

    @ExceptionHandler(UserException.class)
    public ResponseEntity<?> handleUserException(Exception e) {
        return ResponseEntity.badRequest().body(
                MessageResponse.of(ResponseCode.FAIL));
    }

}
  • 예외 처리는 @RestControllerAdvice를 사용하였다.
  • 유효성 검증 에러 외에는 UserException을 통한 기본 에러처리만 하도록하였다.
  • 실패 코드에 대한 세분화 진행 시 활용하여 처리할 예정이다.

4. Spring Security

@Configuration
@EnableWebSecurity
public class SecurityConfig {

    @Bean
    public BCryptPasswordEncoder bCryptPasswordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {

        http.csrf(AbstractHttpConfigurer::disable);

        http.authorizeHttpRequests((auth) -> auth
                .requestMatchers("/**").permitAll()
                .anyRequest().authenticated());

        return http.build();
    }
}
  • Security 설정은 암호화를 위한 Encoder 추가, csrf 비활성화만 진행 하였다.
  • 그 외에 인증/인가 처리 등은 추후 고민해보도록 하자.

이어서

사용자 CRUD기능에 대한 코드는 github를 통해 확인 가능하다.

코드 이력에 중요 정보들이 포함되어 public repository를 새롭게 만들었다.

Repository를 옮긴 방법은 아래 링크를 통해 확인 가능하다.(2024.11.27)

다음은 위에서 나온 것처럼 예외 처리를 세분화 해보도록 하자.

profile
환영합니다!

0개의 댓글