[W3D3]SpringBoot_part1
1.依存注入方法
-作成者注入アレイ
A→B,B→Aを参照すると,ループ依存関係が形成される.
BenCurrentlyInCreationException異常が発生する可能性があります.
package org.prgrms.kdtspringorder;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
class A{
private final B b;
A(B b){
this.b = b;
}
}
class B{
private final A a;
B(A a){
this.a =a;
}
}
@Configuration
class CircularConfig{
@Bean
public A a(B b){
return new A(b);
}
@Bean
B b(A a){
return new B(a);
}
}
public class CircularDepTester {
public static void main(String[] args) {
var AnnotationConfigApplicationContext = new AnnotationConfigApplicationContext(CircularConfig.class);
}
}
2.構成部品スキャンを使用して空の登録を行う
- @Component, @Controller, @Service, @Configuration
-コンポーネントスキャン用に@Repositoryを追加
-メソッドをOrderクラスに追加し、getOrderId,
public UUID getOrderId(){
return orderId;
}
依存関係の注入方法
生成者
Autowired
依存関係注入方法はいろいろありますが、何を使うべきですか?ジェネレータベースの依存関係を注入!!
1初期化時に必要な依存関係をすべて形成するため、安全
2誤ったパターンを見つけるのに役立ちます.コンストラクション関数に複数のパラメータがある場合は、それらの間に多くの依存関係があることを示します.->注目点を分離する必要があります.
3容易なテスト:setフィールドに依存を注入すると、作成されていない空のために空の点が異常になる可能性があります.
4非可視性の確保:コンストラクション関数を注入しないとfinalキーワードを生成できません
finalキーワード:一度に作成した依存関係を維持するのに役立ちます
同じインタフェースが複数のクラスで実装されている場合?
既存のクラスでVoucherRepositoryを実装するJdbcVoucherRepositoryを作成した場合、両方に@Repositoryがあるため、コンポーネントスキャンの2つのターゲットが空に登録されるため、次のエラーが発生します.
解決策?どの空白を自動的に登録するかを選択する必要があります@Primary
1.@primaryを使用して空の登録時に優先順位を付ける
2.名前を明記する
AサーバBサーバCサーバの接続先が異なる
接続を担当するスタンプクラスは同じですが、3つ登録する必要があります.
同じタイプなので、衝突が発生した場合は、品質を利用します.
基本的にはPrimary
Bean Scope
var voucherRepository = BeanFactoryAnnotationUtils.qualifiedBeanOfType(applicationContext.getBeanFactory(),VoucherRepository.class,"memory");
var voucherRepository2 = BeanFactoryAnnotationUtils.qualifiedBeanOfType(applicationContext.getBeanFactory(),VoucherRepository.class,"memory");
System.out.println(MessageFormat.format("voucherRepository {0}",voucherRepository));
System.out.println(MessageFormat.format("voucherRepository2 {0}",voucherRepository));
System.out.println(MessageFormat.format("voucherRepository == voucherRepository2 => {0}", voucherRepository == voucherRepository2));
getBeanのたびに同じオブジェクトが返されます.違うようにしたいなら、プロトタイプを使ってもいいです.
Prototypeを使用しているので、他のオブジェクトが戻ってくることを確認できます.
実行結果
postConstruct called!
afterPropertieSet called!
main 실행
preDestroy called!
destroy called!
public class AppConfiguration {
@Bean(initMethod = "init")
public Beanone beanone(){
return new Beanone();
}
class Beanone implements InitializingBean{
public void init(){
System.out.println("[BeanOne]init called");
}
@Override
public void afterPropertiesSet() throws Exception {
System.out.println("[Beanone] afterPropertiesSet called!");
}
}
Reference
この問題について([W3D3]SpringBoot_part1), 我々は、より多くの情報をここで見つけました https://velog.io/@kcwthing1210/W3D3SpringBootpart1テキストは自由に共有またはコピーできます。ただし、このドキュメントのURLは参考URLとして残しておいてください。
Collection and Share based on the CC Protocol