上述几篇内容都没有涉及到Spring的内容,就是为了更好地阐述Spring的工作原理
如图:
使用Spring的框架,当然要编写appcontent.xml文件:
如下:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN"
"http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
<bean name="fileHelloWorld" class="com.nantian.spring.example4.HelloWorld">
<constructor-arg>
<ref bean="fileHello"/>
</constructor-arg>
</bean>
<bean name="fileHello" class="com.nantian.spring.example4.FileHelloStr">
<constructor-arg>
<value>helloworld.properties</value>
</constructor-arg>
</bean>
</beans>
如图:
再重构HelloWorldClient类:
如下:
/**
*
*/
package com.nantian.spring.example4;
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;
import com.nantian.spring.example4.HelloWorld;
/**
* @author ps
*
*/
public class HelloWorldClient {
protected static final Log log = LogFactory.getLog(HelloWorldClient.class);
public HelloWorldClient() {
Resource resource = new ClassPathResource("com/nantian/spring/example4/appcontent.xml");
BeanFactory factory = new XmlBeanFactory(resource);
HelloWorld helloWorld = (HelloWorld)factory.getBean("fileHelloWorld");
log.info(helloWorld.getContent());
}
/**
* @param args
*/
public static void main(String[] args) {
new HelloWorldClient();
}
}
最后运行HelloWorldClient类输出:
二月 09, 2012 3:55:24 下午 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
信息: Loading XML bean definitions from class path resource [com/nantian/spring/example4/appcontent.xml]
二月 09, 2012 3:55:24 下午 com.nantian.spring.example4.HelloWorldClient <init>
信息: "Hello World!"
开发者还注意到,上述输出结果同前面3个实例有所不同,除了输入本身的信息外,还包括了Spring的输出信息。
但结果是一样的。