inblog logo
|
silver
    프로젝트

    [프로젝트] DTO에 의존성 주입 시도로 인한 오류

    silver's avatar
    silver
    Dec 05, 2024
    [프로젝트] DTO에 의존성 주입 시도로 인한 오류

    🔍 문제 상황

    비밀번호 변경 DTO에서 PasswordEncoder를 생성자 매개변수로 받으려고 시도
    notion image
    public class ChangePwDTO { private String password; private PasswordEncoder passwordEncoder; // ❌ 잘못된 설계 public ChangePwDTO(PasswordEncoder passwordEncoder) { this.passwordEncoder = passwordEncoder; } }
     

    🤔 원인 분석

    1. DTO의 역할 위반
        • DTO는 단순한 데이터 전송 객체(Data Transfer Object)
        • 비즈니스 로직이나 의존성을 포함하면 안 됨
    1. Spring 바인딩 실패
        • Spring이 HTTP 요청을 DTO로 변환할 때, PasswordEncoder 객체를 제공할 수 없음
        • 기본 생성자가 없거나 필요한 매개변수를 알 수 없어 예외 발생

    ✅ 해결 방법

    Service 레이어에서 의존성 처리
    public class ChangePwDTO { private String password; // Getter, Setter만 포함 } // Service - 비즈니스 로직 처리 @Service @RequiredArgsConstructor public class UserService { private final PasswordEncoder passwordEncoder; @Transactional public void 비밀번호변경(ChangePwDTO changePwDTO) { String encodedPassword = passwordEncoder.encode(changePwDTO.getPassword()); // 비밀번호 업데이트 로직 } }
     
    💡
    DTO는 의존성을 가지지 않아야 한다! - DTO: 데이터 전송만 담당 - Service: 비즈니스 로직 및 의존성 처리
    Share article

    silver

    RSS·Powered by Inblog