Spring BeanFactory容器
这是最简单的容器提供DI的基本支持,并由org.springframework.beans.factory.BeanFactory 接口中定义。BeanFactory或者相关的接口,例如实现BeanFactoryAware,InitializingBean,DisposableBean,仍然存在在Spring向后兼容性与大量的 Spring 整合第三方框架的目的。
有相当数量的接口来提供直出随取即用的Spring 的 BeanFactory接口的实现。最常用BeanFactory 实现的是 XmlBeanFactoryclass。此容器从XML文件中读取配置元数据,并使用它来创建一个完全配置的系统或应用程序。
BeanFactory中通常是首选的资源,如移动设备或基于applet的应用受到限制。因此,使用一个ApplicationContext,除非你有一个很好的理由不这样做。
例如:
让我们使用 Eclipse IDE,然后按照下面的步骤来创建一个Spring应用程序:
步骤 | 描述 |
---|---|
1 | 创建一个项目名称为 SpringExample 并创建一个包 com.manongjc 在文件夹 src 下. |
2 | Add 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.manongjc 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. |
这里是HelloWorld.java文件的内容:
package com.manongjc;
public class HelloWorld {
private String message;
public void setMessage(String message){
this.message = message;
}
public void getMessage(){
System.out.println("Your Message : " + message);
}
}
下面是第二个文件 MainApp.java 的内容:
package com.manongjc;
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();
}
}
有以下两个要点需要注意在主要程序中:
-
第一步是创建工厂对象,我们使用的框架API XmlBeanFactory() 来创建工厂bean,并使用ClassPathResource() API来加载在CLASSPATH中可用的bean配置文件。在API 需要 XmlBeanFactory() 创建和初始化所有对象。在配置文件中提到的 bean 类。
-
第二个步骤是用来使用创建的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.manongjc.HelloWorld">
<property name="message" value="Hello World!"/>
</bean>
</beans>
一旦创建源和bean配置文件来完成,让我们运行应用程序。如果一切顺利,您的应用程序,这将打印以下信息:
Your Message : Hello World!