?? hello.java.txt
字號:
package onlyfun.caterpillar;
public class HelloBean {
private String helloWord = "Hello!World!";
public void setHelloWord(String helloWord) {
this.helloWord = helloWord;
}
public String getHelloWord() {
return helloWord;
}
}
HelloBean有預設的"Hello!World!"字符串,我們也可以透過setter來設定新的招呼語,不過我們不親自撰寫程序來作這些事,而是在組態檔案定義,由Spring來為我們作設定的動作,我們撰寫bean.xml:
bean.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 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());
}
}
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -