Spring-autowiring-byconstructor
提供:Dev Guides
コンストラクターによる春の自動配線
このモードは_byType_と非常に似ていますが、コンストラクター引数に適用されます。 Springコンテナは、XML設定ファイルで_autowire_属性が_constructor_に設定されているBeanを調べます。 次に、構成ファイル内のBean名の1つと、コンストラクターの引数を一致させて配線しようとします。 一致するものが見つかると、それらのBeanを注入します。 それ以外の場合、Beanは配線されません。
たとえば、構成ファイルの_constructor_によってBean定義がautowireに設定され、_SpellChecker_型の引数の1つを持つコンストラクターがある場合、Springは_SpellChecker_という名前のBean定義を探し、それを使用してコンストラクターの引数を設定します。 それでも、<constructor-arg>タグを使用して残りの引数を配線できます。 次の例で概念を説明します。
動作するEclipse IDEを用意し、次の手順を実行してSpringアプリケーションを作成します。
Steps | Description |
---|---|
1 | Create a project with a name SpringExample and create a package com.finddevguides under the *src *folder in the created project. |
2 | Add required Spring libraries using Add External JARs option as explained in the Spring Hello World Example chapter. |
3 | Create Java classes TextEditor, SpellChecker and MainApp under the com.finddevguides package. |
4 | Create Beans configuration file Beans.xml under the* src* folder. |
5 | The final step is to create the content of all the Java files and Bean Configuration file and run the application as explained below. |
以下は TextEditor.java ファイルの内容です-
以下は、別の依存クラスファイル SpellChecker.java の内容です-
以下は MainApp.java ファイルの内容です-
以下は通常の状態の設定ファイル Beans.xml です-
しかし、「コンストラクター」で自動配線を使用する場合、XML構成ファイルは次のようになります-
ソースおよびBean構成ファイルの作成が完了したら、アプリケーションを実行しましょう。 すべてがあなたのアプリケーションでうまくいけば、それは次のメッセージを印刷します-