Spring
생성자 의존성 주입시 순환참조
JuBin
2020. 11. 16. 12:54
반응형
간단한 예제코드
@Component
public class ABean {
private BBean b;
public ABean(BBean b) {
this.b=b;
}
public void bMethod() {
b.print();
}
public void print() {
System.out.println("ABean !");
}
}
@Component
public class BBean {
private ABean a;
public BBean(ABean a) {
this.a=a;
}
public void aMethod() {
a.print();
}
public void print() {
System.out.println("BBean !");
}
}
@SpringBootApplication
public class CircularReferenceApplication implements CommandLineRunner{
@Autowired
private ABean a;
@Autowired
private BBean b;
public static void main(String[] args) {
SpringApplication.run(CircularReferenceApplication.class, args);
}
@Override
public void run(String... args) throws Exception {
a.bMethod();
b.aMethod();
}
}
출처: https://coding-start.tistory.com/250?category=738631 [코딩스타트]
생성자 의존성주입의 대한 결과는 아래 코드와 같다. (순환참조)
┌─────┐
| ABean defined in file [/Users/yun-yeoseong/eclipse-study/circular-reference/target/classes/com/example/demo/ABean.class]
↑ ↓
| BBean defined in file [/Users/yun-yeoseong/eclipse-study/circular-reference/target/classes/com/example/demo/BBean.class]
└─────┘
출처: https://coding-start.tistory.com/250?category=738631 [코딩스타트]
이유는 생성자, 필드, 세터 이 3가지의 라이프사이클을 생각해보면 쉽다.
필드와 세터의 의존성주입은 각 메소드를 이용해 의존성주입을 하게된다. 바로 해당 객체가 메모리에 올라간 후 빈을 주입하게 되서 순환참조 예외가 발생하지 않는것이다.
하지만 생성자 의존성주입은 객체가 생성 되자마자 필요한 빈을 의존성주입 하기때문에(메모리에 채 올라가기도 전에)
순환참조 예외가 발생하는 것이다.
객체지향 설계에서 객체의 의존에 순환관계가 있다면 잘못 설계된 객체인지 살펴볼 필요가 있다.
반응형