본문 바로가기
IT개발/Spring5

[Spring5]HTTP 상태 500 – UnsatisfiedDependencyException (메시지 서블릿 [dispatcher]을(를) 위한 Servlet.init() 호출이 예외를 발생)

by Thompson 2024. 11. 18.
728x90
반응형

Spring에서 트랜잭션을 적용한 비밀번호 변경 서비스 오류 해결 사례

예외 발생 메시지

 

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'controllerConfig': Unsatisfied dependency expressed through field 'changePasswordService'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'changePwdSvc': Unsatisfied dependency expressed through method 'changePassword' parameter 0; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'java.lang.String' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}

 

문제 코드
package model;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

public class ChangePasswordService {
    private CustomerDao customerDao;

    // 세터를 통한 의존성 주입
    public void setCustomerDao(CustomerDao customerDao) {
        this.customerDao = customerDao;
    }

    // 비밀번호 변경을 수행하는 메서드
    @Autowired // 의존성 주입
    public void changePassword(String email, String oldPwd, String newPwd) {
        Customer customer = customerDao.selectByEmail(email);
        if (customer == null)
            throw new CustomerNotFoundException();

        customer.changePassword(oldPwd, newPwd);
        customerDao.update(customer);
    }
}
문제 발생
  • Spring 프레임워크를 사용하여 ChangePasswordService 클래스에서 비밀번호 변경 로직을 구현하는 중에 오류가 발생했습니다. 위와 같은 코드를 작성한 후, @Autowired 대신 @Transactional 어노테이션을 적용해야 하는 상황.
문제 해결
  • 이 코드는 @Autowired 어노테이션을 changePassword 메서드에 적용하려 했습니다. 하지만 Spring에서 @Autowired 어노테이션은 필드나 생성자에 주로 사용되기에 그 결과, @Autowired가 정상적으로 작동하지 않아 의존성 주입이 이루어지지 않는 문제가 발생했습니다.
문제 해결 코드
	@Bean // Spring IoC 컨테이너에 ChangePasswordService 빈을 등록
	public ChangePasswordService changePwdSvc() {
		ChangePasswordService pwdSvc = new ChangePasswordService(); // ChangePasswordService 객체 생성
		pwdSvc.setCustomerDao(customerDao()); // ChangePasswordService에 CustomerDao 객체를 주입
		return pwdSvc; // ChangePasswordService 객체 반환
	}
package model;

import org.springframework.transaction.annotation.Transactional;

public class ChangePasswordService {
    private CustomerDao customerDao;

    // 세터를 통한 의존성 주입
    public void setCustomerDao(CustomerDao customerDao) {
        this.customerDao = customerDao;
    }

    // 비밀번호 변경을 수행하는 메서드
    @Transactional  // 트랜잭션 처리를 위해 추가
    public void changePassword(String email, String oldPwd, String newPwd) {
        Customer customer = customerDao.selectByEmail(email);
        if (customer == null)
            throw new CustomerNotFoundException();  // 고객이 존재하지 않으면 예외 처리

        customer.changePassword(oldPwd, newPwd);  // 비밀번호 변경
        customerDao.update(customer);  // 데이터베이스에 업데이트
    }
}