Spring Bootが循環依存の問題をどのように解決するか
Spring Bootにおける循環依存の問題を解決するには、いくつかの方法があります。
- オートワイヤード
@Component
public class A {
private B b;
@Autowired
public A(B b) {
this.b = b;
}
}
@Component
public class B {
private A a;
@Autowired
public B(A a) {
this.a = a;
}
}
- ものぐさな
- 面倒くさがり屋
@Component
public class A {
@Autowired
@Lazy
private B b;
}
@Component
public class B {
@Autowired
@Lazy
private A a;
}
- Springによって自動的に有線接続される
@Component
public class A {
private B b;
@Autowired
public void setB(B b) {
this.b = b;
}
}
@Component
public class B {
private A a;
@Autowired
public void setA(A a) {
this.a = a;
}
}
- @PostConstruct()
- @PostConstruct
@Component
public class A {
private B b;
@Autowired
public void setB(B b) {
this.b = b;
}
@PostConstruct
public void init() {
b.setA(this);
}
}
@Component
public class B {
private A a;
@Autowired
public void setA(A a) {
this.a = a;
}
@PostConstruct
public void init() {
a.setB(this);
}
}
これらは循環依存問題を解決するために一般的に使われる手法で、具体的なシナリオやニーズに基づいて適切な手法を選択してください。