
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'
@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;
}
@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);
}
}
@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));
}
}
@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();
}
}
사용자 CRUD기능에 대한 코드는 github를 통해 확인 가능하다.
코드 이력에 중요 정보들이 포함되어 public repository를 새롭게 만들었다.
Repository를 옮긴 방법은 아래 링크를 통해 확인 가능하다.(2024.11.27)
다음은 위에서 나온 것처럼 예외 처리를 세분화 해보도록 하자.