SpringIOC的一个小例子 有一处不明白

m11418166 m11418166 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区

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>


这个例子的意思是 让一个人 在国内的时候说中文 大家好 在国外说helloworld 很简单的SpringIOC 小例子
但是有一点不明白 Person类中的 return this.helloMessage2.sayHello(); 这句话不明白 这句话的目的是什么啊 为什么要写这句话。
...全文

相关推荐

评论 8
收藏 已收藏
分享
返回顶部
m11418166
Java SE 62,620 成员 307,251 内容