Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | ||
6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 | 28 | 29 | 30 |
Tags
- wagon-ssh
- Kotlin
- try-with-resources
- springboot
- 동작방식
- Runtime data area
- resilience4j
- jetbrain
- zipWith
- try-catch-finally
- 4-way-handshake
- closeable
- webflux
- AutoCloseable
- 람다표현식
- n+1
- jvm
- java
- execution engine
- feign
- optional
- 코딩테스트
- circuitbreaker
- Class Loader
- intelij
- GC
- try-catch
- tcp
- 날짜쿼리
- Hotspot VM
Archives
- Today
- Total
JuBin's personal study blog
생성자 의존성 주입시 순환참조 본문
반응형
간단한 예제코드
@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가지의 라이프사이클을 생각해보면 쉽다.
필드와 세터의 의존성주입은 각 메소드를 이용해 의존성주입을 하게된다. 바로 해당 객체가 메모리에 올라간 후 빈을 주입하게 되서 순환참조 예외가 발생하지 않는것이다.
하지만 생성자 의존성주입은 객체가 생성 되자마자 필요한 빈을 의존성주입 하기때문에(메모리에 채 올라가기도 전에)
순환참조 예외가 발생하는 것이다.
객체지향 설계에서 객체의 의존에 순환관계가 있다면 잘못 설계된 객체인지 살펴볼 필요가 있다.
반응형
'Spring' 카테고리의 다른 글
[Spring] Dependency Injection (0) | 2024.04.28 |
---|---|
[Reactor] zipWith(webflux reactor) 함수 (0) | 2021.10.05 |
[Spring] Spring WebFlux + SpringBoot로 간단한 이커머스 플랫폼 개발 - 1(개념정리) (0) | 2021.09.09 |
Spring Security CORS 설정 (0) | 2021.06.23 |
Spring Boot 정리 (0) | 2020.09.20 |