且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

spring IoC编程实例

更新时间:2022-10-02 23:01:38

配置文件

/SpringHelloWorld/src/applicationContext.xml

 


  1. 代码  
  2.  
  3. <?xml version="1.0" encoding="UTF-8"?> 
  4. <beans 
  5.     xmlns="http://www.springframework.org/schema/beans" 
  6.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
  7.     xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd"> 
  8.       
  9.     <bean id="greetingService" class="com.qdu.sun.spring.HelloWorld"> 
  10.         <constructor-arg> 
  11.             <value type="java.lang.String">Welcome!</value> 
  12.         </constructor-arg> 
  13.     </bean></beans> 

SpringTest.java

 


  1. 代码  
  2.  
  3. package com.qdu.sun.spring;  
  4.  
  5. import org.springframework.beans.factory.BeanFactory;  
  6. import org.springframework.beans.factory.xml.XmlBeanFactory;  
  7. import org.springframework.core.io.ClassPathResource;  
  8.  
  9. public class SpringTest {  
  10.      public static void main( String[] args ){  
  11.             BeanFactory factory = new XmlBeanFactory( new ClassPathResource("applicationContext.xml") );  
  12.             HelloWorld gc = (HelloWorld)factory.getBean("greetingService");  
  13.             gc.sayGreeting();  
  14.         }  

HelloWorld.java

 


  1. 代码  
  2.  
  3. package com.qdu.sun.spring;  
  4.  
  5. public class HelloWorld {  
  6. private String greeting;  
  7.       
  8.     public HelloWorld(){  
  9.           
  10.     }  
  11.       
  12.     public HelloWorld( String greeting ){  
  13.         this.greeting = greeting;  
  14.     }  
  15.       
  16.     public void sayGreeting(){  
  17.         System.out.println( greeting );  
  18.     }  
  19.       
  20.     public void setGreeting( String greeting ){  
  21.         this.greeting = greeting;  
  22.     }  
  23.  

 


本文转自linzheng 51CTO博客,原文链接:http://blog.51cto.com/linzheng/1080804