Java笔记9:Spring简单Demo

 

1 下载spring-framework-3.0.5.RELEASE-with-docs.zip和spring-framework-3.0.5.RELEASE-dependencies.zip,放在任意目录下,比如我是放在D:DownloadJava中并解压缩

 

2 用Eclispe建立一个名为MySpring的动态Web工程。我这里的工程目录为E:ProjectsMySpring

 

3 把D:DownloadJavaspring-framework-3.0.5.RELEASEdist中的所有文件复制到E:ProjectsMySpringWebContentWEB-INFlib中

D:DownloadJavaspring-framework-3.0.5.RELEASE-dependencies中的所有文件复制到E:ProjectsMySpringWebContentWEB-INFlib中

 

4 刷新myspring工程

 

在工程中可以看到spring相关的包已经被加载进来

 

5 在src目录下创建PersonService.java,内容为

 

[java] view plain copy
 
 在CODE上查看代码片派生到我的代码片
  1. public class PersonService {  
  2.   
  3.     private String name;  
  4.   
  5.     //name属性的setter方法  
  6.   
  7.     public void setName(String name)  
  8.   
  9.     {  
  10.   
  11.         this.name = name;  
  12.   
  13.     }  
  14.   
  15.     //测试Person类的info方法  
  16.   
  17.     public void info()  
  18.   
  19.     {  
  20.   
  21.         System.out.println("此人名为:"   
  22.   
  23.             + name);  
  24.   
  25.     }  
  26.   
  27. }  

 

src目录下创建SpringTest.java,内容为

 

[java] view plain copy
 
 在CODE上查看代码片派生到我的代码片
  1. import org.springframework.context.ApplicationContext;  
  2.   
  3. import org.springframework.context.support.ClassPathXmlApplicationContext;  
  4.   
  5.    
  6.   
  7. public class SpringTest {  
  8.   
  9.    
  10.   
  11.     public static void main(String[] args) {  
  12.   
  13.         //创建Spring的ApplicationContext  
  14.   
  15.         ApplicationContext ctx = new ClassPathXmlApplicationContext  
  16.   
  17.          ("bean.xml");  
  18.   
  19.         //输出Spring容器  
  20.   
  21.         System.out.println(ctx);  
  22.   
  23.         PersonService p = ctx.getBean("personService" , PersonService.class);  
  24.   
  25.         p.info();  
  26.   
  27.     }  
  28.   
  29. }  


src目录下创建bean.xml,内容为

 

[html] view plain copy
 
 在CODE上查看代码片派生到我的代码片
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2.   
  3. <beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  4.   
  5.     xmlns="http://www.springframework.org/schema/beans"  
  6.   
  7.     xsi:schemaLocation="http://www.springframework.org/schema/beans  
  8.   
  9.     http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">  
  10.   
  11.     <!-- 将PersonService类部署成Spring容器中的Bean  -->  
  12.   
  13.     <bean id="personService" class="PersonService">  
  14.   
  15.         <property name="name" value="wawa"/>  
  16.   
  17.     </bean>  
  18.   
  19. </beans>  


至此,src下的文件目录结构为

 

 

6 运行StringTest.java,显示结果

 

 

程序结果正常运行出来。

有两个log4j相关的警告,这里可以先忽略。

原文地址:https://www.cnblogs.com/grimm/p/6732427.html