Spring Bootが循環依存の問題をどのように解決するか

Spring Bootにおける循環依存の問題を解決するには、いくつかの方法があります。

  1. オートワイヤード
@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;
}
}
  1. ものぐさな
  2. 面倒くさがり屋
@Component
public class A {
@Autowired
@Lazy
private B b;
}
@Component
public class B {
@Autowired
@Lazy
private A a;
}
  1. 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;
}
}
  1. @PostConstruct()
  2. @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);
}
}

これらは循環依存問題を解決するために一般的に使われる手法で、具体的なシナリオやニーズに基づいて適切な手法を選択してください。

コメントを残す 0

Your email address will not be published. Required fields are marked *


广告
広告は10秒後に閉じます。
bannerAds