1.Spring IoC简单例子
Spring IoC简单例子
1.IHelloMessage.java
1 package com.tony.spring.chapter01; 2 3 public interface IHelloMessage { 4 public String sayHello(); 5 }
2.HelloWorld.java
1 package com.tony.spring.chapter01; 2 3 public class HelloWorld implements IHelloMessage { 4 5 @Override 6 public String sayHello() { 7 return "Hello everyone"; 8 } 9 10 }
3.HelloChina.java
1 package com.tony.spring.chapter01; 2 3 public class HelloChina implements IHelloMessage { 4 5 @Override 6 public String sayHello() { 7 return "大家好"; 8 } 9 10 }
4.Person.java
1 package com.tony.spring.chapter01; 2 3 public class Person { 4 5 private IHelloMessage helloMessage; 6 7 public IHelloMessage getHelloMessage() { 8 return helloMessage; 9 } 10 11 public void setHelloMessage(IHelloMessage helloMessage) { 12 this.helloMessage = helloMessage; 13 } 14 15 public String sayHello(){ 16 return helloMessage.sayHello(); 17 } 18 }
5.Main.java
1 package com.tony.spring.chapter01; 2 3 import org.springframework.beans.factory.BeanFactory; 4 import org.springframework.beans.factory.xml.XmlBeanFactory; 5 import org.springframework.core.io.FileSystemResource; 6 import org.springframework.core.io.Resource; 7 8 public class Main { 9 10 public static void main(String[] args) { 11 Resource r = new FileSystemResource("helloMessage.xml"); 12 BeanFactory f = new XmlBeanFactory(r); 13 Person person = (Person)f.getBean("person"); 14 String s = person.sayHello(); 15 System.out.println("他说"+s); 16 } 17 18 }
6.helloMessage.xml
1 <?xml version="1.0" encoding="UTF-8"?> 2 <!DOCTYPE beans PUBLIC "-//SPRING/DTD BEAN/EN" 3 "http://www.springframework.org/dtd/spring-beans.dtd"> 4 <beans> 5 <bean id="helloWorld" class="com.tony.spring.chapter01.HelloWorld"></bean> 6 <bean id="helloChina" class="com.tony.spring.chapter01.HelloChina"></bean> 7 <bean id="person" class="com.tony.spring.chapter01.Person"> 8 <!--<property name="helloMessage" ref="helloChina"/>--> 9 <property name="helloMessage" ref="helloWorld"/> 10 </bean> 11 </beans>
You can do anything you set your mind to, man!