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的实例。