Spring是什麼,這裏就不介紹了,簡單的來說,Spring就是一個可以簡化我們開發的框架,它的結構圖如下:
它的最基礎的包有Beans、Core、Context、Expression、Context-support。
Spring怎麼容納我們的程序呢?
我們寫一個最簡單的基於XML配置的Spring程序,由Spring管理我們的Bean。例子是人類打電話。Spring的設計原則是面向接口編程,所以我們也基於這個原則設計代碼。
電話接口(Phone):
public interface Phone {
void call();
}
人類接口(Human):
public interface Human {
void call();
}
寫兩個實現:
座機實現(TelePhone):
public class TelePhone implements Phone{
public void call() {
System.out.println("I am calling by telephone!");
}
}
中國人實現(ChaneseHuman):
public class ChaneseHuman implements Human{
private Phone phone;
public void call() {
phone.call();
}
public void setPhone(Phone phone) {
this.phone = phone;
}
}
resources下建一個文件夾spring,spring下建立一個文件pen.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.xsd">
<bean name="phone" class="TelePhone">
</bean>
<bean name="human" class="ChaneseHuman">
<property name="phone" ref="phone"/>
</bean>
</beans>
寫我們的執行類(TestMain):
public class TestMain {
public static void main(String[] args) {
ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring/pen.xml");
Human human = (Human)applicationContext.getBean("human");
human.call();
}
}
執行結果:
Dec 31, 2017 11:54:59 AM org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@2d6e8792: startup date [Sun Dec 31 11:54:58 CST 2017]; root of context hierarchy
Dec 31, 2017 11:54:59 AM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [spring/pen.xml]
I am calling by telephone!
最簡單的一個Spring管理我們的各種class的實例。