62,615
社区成员
发帖
与我相关
我的任务
分享
package com.jike.spring.chapter01;
//接口
public interface IHelloMessage {
public String sayHello();
}
package com.jike.spring.chapter01;
public class HelloChina implements IHelloMessage {
@Override
public String sayHello() {
return "大家好";
}
}
package com.jike.spring.chapter01;
public class HelloWorld implements IHelloMessage {
@Override
public String sayHello() {
return "Hello World!";
}
}
package com.jike.spring.chapter01;
public class Person {
//因为Person类需要引用 IHelloMessage 所以要把IHelloMessage写成一个属性
private IHelloMessage helloMessage;
public IHelloMessage getHelloMessage() {
return helloMessage;
}
public void setHelloMessage(IHelloMessage helloMessage) {
this.helloMessage = helloMessage;
}
public String sayHello(){
return this.helloMessage.sayHello(); //调用IHelloMessage这个接口来输出问候信息
}
}
package com.jike.spring.chapter01;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
public class Main {
public static void main(String[] args) {
//利用FileSystemResource 来读取配置文件
Resource r = new FileSystemResource("helloMessage.xml");
//使用XmlBeanFactory来加载配置文件 启动IOC容器
BeanFactory f = new XmlBeanFactory(r);
//从IOC容器中获取Person类的实例
Person lizi = (Person)f.getBean("chaoji");
//需要用Person实例来输出问候信息
String s = lizi.sayHello();
System.out.println(s);
}
}
<?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 = "helloWorld" class = "com.jike.spring.chapter01.HelloWorld">
</bean>
<bean id = "helloChina" class = "com.jike.spring.chapter01.HelloChina">
</bean>
<bean id = "chaoji" class = "com.jike.spring.chapter01.Person">
<property name = "helloMessage" ref = "helloWorld">
</property>
</bean>
</beans>