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); // 데이터베이스에 업데이트
}
}
'IT개발 > Spring5' 카테고리의 다른 글
[Spring5] 커맨드 객체 검증(Validate(), @Valid, Bean Validation) (0) | 2024.11.24 |
---|---|
[Spring & MVC] MVC의 이해 (0) | 2024.11.18 |
[Spring/스프링] AOP(Aspect Oriented Programming) 주요 용어 (0) | 2024.04.13 |
[Spring, 스프링] 프레임워크(FrameWork) ,컨테이너(Container) (0) | 2024.04.06 |
[Spring, 스프링] AOP(Aspect Oriented Programming)의 주요 용어 (0) | 2024.04.05 |