这是一个最简单的容器,它主要的功能是为依赖注入 (di) 提供支持,这个容器接口在 org.springframework.beans.factory.beanfactor 中被定义。beanfactory 和相关的接口,比如beanfactoryaware、disposablebean、initializingbean,仍旧保留在 spring 中,主要目的是向后兼容已经存在的和那些 spring 整合在一起的第三方框架。
在 spring 中,有大量对 beanfactory 接口的实现。其中,最常被使用的是 xmlbeanfactory 类。这个容器从一个 xml 文件中读取配置元数据,由这些元数据来生成一个被配置化的系统或者应用。
在资源宝贵的移动设备或者基于 applet 的应用当中, beanfactory 会被优先选择。否则,一般使用的是 applicationcontext,除非你有更好的理由选择 beanfactory。
假设我们已经安装 eclipse ide,按照下面的步骤,我们可以创建一个 spring 应用程序。
步骤 | 描述 |
---|---|
1 | 创建一个名为 springexample 的工程并在 src 文件夹下新建一个名为 com.tutorialspoint 文件夹。 |
2 | 点击右键,选择 add external jars 选项,导入 spring 的库文件,正如我们在 spring hello world example 章节中提到的导入方式。 |
3 | 在 com.tutorialspoint 文件夹下创建 helloworld.java 和 mainapp.java 两个类文件。 |
4 | 在 src 文件夹下创建 bean 的配置文件 beans.xml |
5 | 最后的步骤是创建所有 java 文件和 bean 的配置文件的内容,按照如下所示步骤运行应用程序。 |
下面是文件 helloworld.java 的内容:
package com.tutorialspoint;
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.tutorialspoint;
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();
}
}
在主程序当中,我们需要注意以下两点:
第一步利用框架提供的 xmlbeanfactory() api 去生成工厂 bean 以及利用 classpathresource() api 去加载在路径 classpath 下可用的 bean 配置文件。xmlbeanfactory() api 负责创建并初始化所有的对象,即在配置文件中提到的 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.tutorialspoint.helloworld">
<property name="message" value="hello world!"/>
</bean>
</beans>
如果你已经完成上面的内容,接下来,让我们运行这个应用程序。如果程序没有错误,你将从控制台看到以下信息:
your message : hello world!