
本站地址:http://www.bajiao123.com

Spring
package onlyfun.caterpillar;
public class HelloBean {
private String helloWord = "Hello!World!";
public void setHelloWord(String helloWord) {
this.helloWord = helloWord;
}
public String getHelloWord() {
return helloWord;
}
}
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING/DTD BEAN/EN" "http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
<bean id="helloBean" class="onlyfun.caterpillar.HelloBean">
<property name="helloWord"><value>Hello!Justin!</value></property>
</bean>
</beans>
bean.xml中定义了JavaBean的别名与来源类别,<property>标签中设定了我们希望注入至JavaBean的字符串值,bean.xml必须在您的CLASSPATH可以存取到的目录中,也许是现行的工作目录,在Web程序中可以是在classes目录下,我们这边使用的是单机程序的方式,将使用FileInputStream读取bean.xml,所以将之置于现行的工作目录中,接着我们撰写一个简单的测试程序: SpringTest.java
package onlyfun.caterpillar;
import java.io.*;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
public class SpringTest {
public static void main(String[] args) throws IOException {
InputStream is = new FileInputStream("bean.xml");
BeanFactory factory = new XmlBeanFactory(is);
HelloBean hello = (HelloBean) factory.getBean("helloBean");
System.out.println(hello.getHelloWord());
}
}
2004/10/21 上午 10:28:00 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions 信息: Loading XML bean definitions from resource for InputStream 2004/10/21 上午 10:28:00 org.springframework.beans.factory.support.AbstractBeanFactory getBean 信息: Creating shared instance of singleton bean 'helloBean' Hello!Justin!
如果今天您要想改变招呼语,则只要更改bean.xml就可以了,不用修改主要的程序,从比较一般的角度来看,就意味着如果您想要改变一些对象之间的依赖关系,则只要修改组态档即可,而不用修改组件的任何一行程序。(
本站地址:http://www.bajiao123.com

