public interface IHelloMessage {
public String sayHello();
}
HelloWorld:接口的實現類,向用戶輸出“Hello everybody”信息public class HelloWorld implements IHelloMessage{
public String sayHello() {
return "Hello Everybody";
}
}
HelloChina:接口的實現類,向用戶輸出“大家好!”信息public class HelloChina implements IHelloMessage{
public String sayHello() {
return "大家好!";
}
}
Person:一個人物類,調用IHelloMessage接口,向用戶輸出問候信息public class Person {
//因爲Person類要引用IHelloMessage接口,所以將IHelloMessage作爲類的一個屬性
private IHelloMessage iHelloMessage;
/**
* 自動生成get方法
* @return
*/
public IHelloMessage getiHelloMessage() {
return iHelloMessage;
}
/**
* 自動生成set方法
* @param iHelloMessage
*/
public void setiHelloMessage(IHelloMessage iHelloMessage) {
this.iHelloMessage = iHelloMessage;
}
/**
* person類使用sayHello方法來調用藉口的sayHello方法
* @return
*/
public String sayHello(){
return this.iHelloMessage.sayHello();
}
}
Main:程序的入口類,用於加載配置文件以及啓動IOC容器,調用人物類,向用戶輸出問候信息
public class Main {
public static void main(String[] args){
//使用FileSystemResource來讀取配置文件
Resource r=new FileSystemResource("helloMessage.xml");
//使用XmlBeanFactory加載配置信息,啓動IOC容器
//Spring3.1之後已經廢棄XmlBeanFactory
//BeanFactory b=new XmlBeanFactory(r);
DefaultListableBeanFactory factory=new DefaultListableBeanFactory();
XmlBeanDefinitionReader reader=new XmlBeanDefinitionReader(factory);
reader.loadBeanDefinitions(r);
//從IOC容器中獲取Person類的實例
//Person person=(Person)b.getBean("Person");
Person person= (Person) factory.getBean("Person");
//使用person類示例來輸出問候信息
String s=person.sayHello();
System.out.println("The Person is currently saying "+s);
}
}
接下來,爲示例代碼建立配置文件helloMessage.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 id="HelloChina" class="cn.lovepi.chapter01.HelloChina">
</bean>
<bean id="HelloWorld" class="cn.lovepi.chapter01.HelloWorld">
</bean>
<bean id="Person" class="cn.lovepi.chapter01.Person">
<!--bean中屬性配置,屬性即爲類中所聲明的接口變量。給其添加了一個引用-->
<property name="iHelloMessage" ref="HelloWorld">
</property>
</bean>
</beans>