を適用するための適切な春のブート方法です私は現在、その次のように(大きく簡略化した例)で一緒にワイヤーいくつかの豆春のブートアプリケーションに取り組んでいます:しかし依存性注入
@Component
@Order(0)
public class PlayingFieldByBeans implements CommandLineRunner {
@Override
public void run(String... arg0) throws Exception {
List<String> names = new ArrayList<>();
names.add("Alex");
names.add("Benedict");
names.add("Chloe");
System.out.println("Printing from lazy beans variant: ");
names.forEach(n -> {
System.out.println(player(n));
});
}
@Bean
@Lazy
public Player player(String name) {
return new Player(name, shoes());
}
@Bean
@Lazy
private Shoes shoes() {
return new Shoes("Adidas");
}
}
実際の豆ここに示したより多くの設定と設定が必要であり、内部のLazy Beanメソドロジを使用する場合、PlayingFieldByBeansクラスのコード行がかなり多くなります。だから私はComponent
アノテーションを使ってそれを一緒に配線するさまざまな方法を作成しました:
@Component
@Order(1)
public class PlayingFieldByComponents implements CommandLineRunner {
@Autowired
private PlayerComponent playerComponent;
@Override
public void run(String... arg0) throws Exception {
List<String> names = new ArrayList<>();
names.add("Alex");
names.add("Benedict");
names.add("Chloe");
System.out.println("Printing from component variant: ");
names.forEach(n -> {
System.out.println(playerComponent.player(n));
});
}
}
PlayerComponentクラスには、次のようになります。
@Component
public class PlayerComponent {
@Autowired
private ShoesComponent shoesComponent;
public Player player(String name) {
return new Player(name, shoesComponent.shoes());
}
}
ShoesComponentがPlayerComponentクラスに非常によく似ています。
メンテナンスとTDDの目的のために、ここで春のフレームワークを使用する最も適切な方法は何か分かりません。プレーヤーや靴豆を考える
質問
は、初期化のちょうど1ライン(複数の設定、その他の豆類などに複数の依存関係)をより多くを必要とし、それらを設計し、配線するための最良の方法は何ですか?
@Configuration
public class BeanConfiguration {
@Bean
@Lazy
public Player player(String name) {
return new Player(name, shoes());
}
@Bean
@Lazy
public Shoes shoes() {
return new Shoes("Adidas");
}
}
マッチング実行クラス:
@Component
@Order(2)
public class PlayingFieldByConfiguration implements CommandLineRunner {
@Autowired
private BeanConfiguration beanConfiguration;
@Override
public void run(String... arg0) throws Exception {
List<String> names = new ArrayList<>();
names.add("Alex");
names.add("Benedict");
names.add("Chloe");
System.out.println("Printing from component variant: ");
names.forEach(n -> {
System.out.println(beanConfiguration.player(n));
});
}
}
Reが同じ第1の豆を使用 -
編集豆をバンドルするために提案
追加されたコンフィギュレーション・クラスに基づいて、新しいものを作成していないようです。
Printing from component variant:
Player name: Alex has shoes of brand: Adidas
Player name: Alex has shoes of brand: Adidas
Player name: Alex has shoes of brand: Adidas
あなたは春にConfiguration'コンポーネント@ 'を見ていましたか?このように、すべてのBeanの初期化コードをそこに置くために必要なものになるでしょう。 –
が –
豆は「新返す」と思われても、デフォルトでシングルトンであるあなたに感謝、あなたの提案と質問を更新し、複数のオブジェクトを作成します。 @Scope(BeanDefinition.SCOPE_PROTOTYPE)を使用する –