Spring-beanfactory-container
Spring BeanFactoryコンテナ
これは、DIの基本的なサポートを提供し、org.springframework.beans.factory.BeanFactoryインターフェースによって定義される最も単純なコンテナーです。 BeanFactoryおよび関連するインターフェース(BeanFactoryAware、InitializingBean、DisposableBeanなど)は、Springと統合する多数のサードパーティフレームワークとの下位互換性を目的として、Springに引き続き存在します。
Springにはすぐに使用できるBeanFactoryインターフェースの実装が多数あります。 最も一般的に使用されるBeanFactory実装は XmlBeanFactory クラスです。 このコンテナは、XMLファイルから構成メタデータを読み取り、それを使用して完全に構成されたシステムまたはアプリケーションを作成します。
通常、BeanFactoryは、モバイルデバイスやアプレットベースのアプリケーションのようにリソースが制限されている場合に推奨されます。 したがって、そうしない理由がない限り、ApplicationContextを使用してください。
例
動作中のEclipse IDEを見て、次の手順を実行してSpringアプリケーションを作成しましょう-
Steps | Description |
---|---|
1 | Create a project with a name SpringExample and create a packagecom.finddevguides under the *src *folder in the created project. |
2 | Add the required Spring libraries using Add External JARs option as explained in the Spring Hello World Example chapter. |
3 | Create Java classes HelloWorld and MainApp under the com.finddevguidespackage. |
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. Finally, run the application as explained below. |
*HelloWorld.java* ファイルの内容は次のとおりです-
package com.finddevguides;
public class HelloWorld {
private String message;
public void setMessage(String message){
this.message = message;
}
public void getMessage(){
System.out.println("Your Message : " + message);
}
}
2番目のファイル MainApp.java の内容は次のとおりです。
package com.finddevguides;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
public class MainApp {
public static void main(String[] args) {
XmlBeanFactory factory = new XmlBeanFactory (new ClassPathResource("Beans.xml"));
HelloWorld obj = (HelloWorld) factory.getBean("helloWorld");
obj.getMessage();
}
}
次の2つの重要な点は、メインプログラムについて注意する必要があります-
- 最初のステップは、フレームワークAPIXmlBeanFactory()を使用してファクトリBeanとClassPathResource()APIを作成し、CLASSPATHで使用可能なBean構成ファイルをロードするファクトリオブジェクトを作成することです。 XmlBeanFactory()APIは、すべてのオブジェクトの作成と初期化、つまり 構成ファイルに記載されているBean。
- 2番目のステップは、作成されたBeanファクトリオブジェクトのgetBean()メソッドを使用して必要なBeanを取得するために使用されます。 このメソッドはBean IDを使用して、最終的に実際のオブジェクトにキャストできる汎用オブジェクトを返します。 オブジェクトを取得したら、このオブジェクトを使用して任意のクラスメソッドを呼び出すことができます。
Bean構成ファイル Beans.xml の内容は次のとおりです。
<?xml version = "1.0" encoding = "UTF-8"?>
<beans xmlns = "http://www.springframework.org/schema/beans"
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation = "http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id = "helloWorld" class = "com.finddevguides.HelloWorld">
<property name = "message" value = "Hello World!"/>
</bean>
</beans>
ソースおよびBean構成ファイルの作成が完了したら、アプリケーションを実行しましょう。 すべてがあなたのアプリケーションでうまくいけば、それは次のメッセージを印刷します-
Your Message : Hello World!