스프링에서 @RequiredArgsConstructor를
권장하는 이유는 크게 2가지인데 순환 참조 방지,객체 변이 방지(final)가 있다
그 중에서도 순환 참조 방지가 좀 헷갈리는거 같아서 정리 해본다.
@Component
public class AService {
private BService bService;
@Autowired
public void setBService(BService bService) {
this.bService = bService;
}
public BService getBService() {
return bService;
}
}
@Component
public class BService {
private AService aService;
@Autowired
public void setAService(AService aService) {
this.aService = aService;
}
public AService getAService() {
return aService;
}
}
위에서 부터 보면
@Component 어노테이션이 적용되어 Spring에 의해 Bean으로 등록된다.
BService 타입의 bService 필드가 선언되어 있다.
setBService() 메서드가 정의되어 있으며, @Autowired 어노테이션이 적용되어 있다.
이는 Spring이 해당 메서드를 호출하여 bService 필드를 주입하도록 지정한다.
즉, AService 객체가 생성될 때 Spring은 BService의 인스턴스를 자동으로 주입하여 해당 필드를 초기화한다.
아래도 마찬가지로 동작한다.
public class Main {
public static void main(String[] args) {
AService aService = new AService();
BService bService = new BService();
aService.setBService(bService); // AService 객체의 상태를 변경함
bService.setAService(aService); // BService 객체의 상태를 변경함
// 객체의 상태 변이가 발생함
}
}
거기에 이런 코드가 있다면 객체의 변이까지 발생할 수 있기 때문에
@Autowired는 지양해야한다
출처 :
https://velog.io/@kimyeji203/Spring-Autowired%EC%99%80-RequiredArgsConstructor-%EC%B0%A8%EC%9D%B4
'Error > SpringBoot' 카테고리의 다른 글
HttpClient.executeOpen (0) | 2024.07.02 |
---|---|
STS-DB 연동 실패(Could not connect to address) (0) | 2024.02.15 |