简单的Spring实例

来源:互联网 发布:电子商务大数据 编辑:程序博客网 时间:2024/06/14 01:37
编写第一个Spring程序 

HelloWorld接口: 

Java代码  收藏代码
  1. /** 
  2.  *  
  3.  * @Copyright(C),2009-2010 SISE Java Team. 
  4.  * @Author:easinchu 
  5.  * @Email:easinchu@gmail.com  
  6.  * @Description: 
  7.  */  
  8. public interface HelloWorld {  
  9.   
  10.     public void sayHello();  
  11. }  

HelloWorldBean实现类: 
Java代码  收藏代码
  1. /** 
  2.  *  
  3.  * @Copyright(C),2009-2010 SISE Java Team. 
  4.  * @Author:easinchu 
  5.  * @Email:easinchu@gmail.com  
  6.  * @Description: 
  7.  */  
  8. public class HelloWorldBean implements HelloWorld{  
  9.   
  10.     private String helloWorld;  
  11.       
  12.     public void setHelloWorld(String helloWorld) {  
  13.         this.helloWorld = helloWorld;  
  14.     }  
  15.       
  16.     public void sayHello() {  
  17.         System.out.println(helloWorld);  
  18.     }  
  19. }  

Spring XML配置文件ioc-config.xml: 
Xml代码  收藏代码
  1. <bean id="helloWorldBean" class="cn.com.sise.firstapp.HelloWorldBean">  
  2.     <property name="helloWorld">  
  3.         <value>Hello,Welcome To Spring World!</value>  
  4.     </property>  
  5. </bean>  

测试类: 
Java代码  收藏代码
  1. import org.springframework.beans.factory.BeanFactory;  
  2. import org.springframework.beans.factory.xml.XmlBeanFactory;  
  3. import org.springframework.core.io.ClassPathResource;  
  4. import org.springframework.core.io.Resource;  
  5.   
  6. /** 
  7.  *  
  8.  *@Copyright(C),2009-2010 SISE Java Team. 
  9.  *@Author:easinchu 
  10.  *@Email:easinchu@gmail.com  
  11.  *@Description:采用Spring的BeanFactory构造IoC容器. 
  12.  */  
  13. public class FirstSpringDemo {  
  14.       
  15.     public static void main(String []args) {  
  16.         //-----------BeanFactory IoC容器---------------------//  
  17.         //从classpath路径上装载XML的配置信息  
  18.         Resource resource = new ClassPathResource("ioc-config.xml");  
  19.           
  20.         //实例化IOC容器,此时容器并未实例化beans-config.xml所定义的各个受管bean.  
  21.         BeanFactory factory = new XmlBeanFactory(resource);  
  22.           
  23.         /  
  24.           
  25.         //获取受管bean  
  26.         HelloWorld hello = (HelloWorld)factory.getBean("helloWorldBean");  
  27.         hello.sayHello();  
  28.     }  
  29. }  

步骤小结 
①利用XmlBeanFactory读取xml配置文件并建立BeanFactory实例 
②BeanFactory依据配置文件完成依赖注入 
③通过getBean()方法指定Bean名称取得Bean实例 

原创粉丝点击