Spring實例一

新建IHelloWord接口類

package com.djx.spring.chapter01;

public interface IHelloMessage {
	public String sayHello();
}
新建HelloWord類

package com.djx.spring.chapter01;

public class HelloWord implements IHelloMessage {

	public String sayHello() {
		return "HelloWord";
	}
}

新建sayHello類

package com.djx.spring.chapter01;

public class SayChina implements IHelloMessage {
	@Override
	public String sayHello() {
		return "大家好";
	}

}

新建Person類

package com.djx.spring.chapter01;

public class Person {
	private IHelloMessage helloMessage;

	public IHelloMessage getHelloMessage() {
		return helloMessage;
	}

	public void setHelloMessage(IHelloMessage helloMessage) {
		this.helloMessage = helloMessage;
	}
	public String sayHello() {
		return this.helloMessage.sayHello();
	}
}


新建Main類

package com.djx.spring.chapter01;
import org.springframework.*;
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) {
		// TODO Auto-generated method stub
		Resource r=new FileSystemResource("helloMessage.xml");
		BeanFactory f=new XmlBeanFactory(r);
		Person person=(Person) f.getBean("person");
		String s=person.sayHello();
		System.out.println("The perosn is currently saying"+s);
	}
}
新建helloMessage.xml文件

<?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="helloWord" class="com.djx.spring.chapter01.HelloWord"></bean>
	<bean id="sayChina" class="com.djx.spring.chapter01.SayChina"></bean>
    <bean id="person" class="com.djx.spring.chapter01.Person">
	<property name="helloMessage" ref="helloWord"></property>
</bean>
</beans>





發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章