一、定义POJO类 package test; /** * IHelloStr接口 * * @author zxs */ public interface IHelloStr { public String getContent(); } package test; import java.io.InputStream; import java.util.Properties; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * 基于文件形式,读取HelloWorld所需的字符串。 * * @author zxs */ public class FileHelloStrImpl implements IHelloStr { protected static final Log log = LogFactory.getLog(FileHelloStrImpl.class); private String propfilename; public FileHelloStrImpl(String propfilename) { this.propfilename = propfilename; } public String getContent() { String helloworld = ""; try { Properties properties = new Properties(); //读入输入流 InputStream is = getClass().getClassLoader().getResourceAsStream( propfilename); properties.load(is); is.close(); //获得helloworld键对应的取值 helloworld = properties.getProperty("helloworld"); } catch (Exception ex) { log.error("", ex); } return helloworld; } } package test; /** * IHelloWorld接口 * * @author zxs * */ public interface IHelloWorld { public abstract String getContent(); } package test; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * 获得HelloWorld字符串 * * @author zxs */ public class HelloWorld implements IHelloWorld { protected static final Log log = LogFactory.getLog(HelloWorld.class); private IHelloStr helloStr; public void setHelloStr(IHelloStr str) { this.helloStr = str; } public String getContent() { return helloStr.getContent(); } } 二、将上述两个POJO配置在基于XML Schema的Spring XML文件中(beanfactory.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-2.5.xsd"> <bean name="fileHello" class="test.FileHelloStrImpl"> <constructor-arg> <value>helloworld.properties</value> </constructor-arg> </bean> <bean id="helloWorld" class="test.HelloWorld"> <property name="helloStr" ref="fileHello" /> </bean> </beans> 三、构造IoC容器,负责装载上述XML文件 package test; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.xml.XmlBeanFactory; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; /** * HelloWorld客户应用 * * @author zxs */ public class BeanFactoryDemo { protected static final Log log = LogFactory.getLog(BeanFactoryDemo.class); public static void main(String[] args) { //从classpath路径上装载XML配置信息 Resource resource = new ClassPathResource("beanfactory.xml"); //实例化IoC容器,此时,容器并未实例化beanfactory.xml所定义的各个受管Bean BeanFactory factory = new XmlBeanFactory(resource); //获得受管Bean IHelloWorld hw = (IHelloWorld) factory.getBean("helloWorld"); //返回字符串 log.info(hw.getContent()); } }