spring-framework-1.1.1-with-dependencies.zip(含相關 JAR)或精簡版。spring-core.jar、commons-logging.jar(必須)。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"
"https://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>
放在 CLASSPATH 根目錄(如工作目錄或 WEB-INF/classes)。
package onlyfun.caterpillar;
import java.io.*;
import org.springframework.beans.factory.*;
import org.springframework.beans.factory.xml.*;
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()); // 輸出 Hello!Justin!
}
}
setHelloWord() 注入字符串依賴。XmlBeanFactory 讀取 XML 完成裝配。helloBean 為單例,getBean() 返回同一實例。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,**無需修改 Java 代碼**,實現了依賴關係的外部化配置,這是 Spring 乃至現代框架的基石思想。