Java笔记9:Spring简单Demo

来源:互联网 发布:淘宝火车票网上订票 编辑:程序博客网 时间:2024/05/20 07:15

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

 

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

 

3D:\Download\Java\spring-framework-3.0.5.RELEASE\dist\中的所有文件复制到E:\Projects\MySpring\WebContent\WEB-INF\lib\

D:\Download\Java\spring-framework-3.0.5.RELEASE-dependencies\中的所有文件复制到E:\Projects\MySpring\WebContent\WEB-INF\lib\

 

4刷新myspring工程



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



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

public class PersonService {    private String name;    //name属性的setter方法    public void setName(String name)    {        this.name = name;    }    //测试Person类的info方法    public void info()    {        System.out.println("此人名为:"             + name);    }}

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

import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext; public class SpringTest {     public static void main(String[] args) {        //创建Spring的ApplicationContext        ApplicationContext ctx = new ClassPathXmlApplicationContext         ("bean.xml");        //输出Spring容器        System.out.println(ctx);        PersonService p = ctx.getBean("personService" , PersonService.class);        p.info();    }}

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

<?xml version="1.0" encoding="UTF-8"?><beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"    xmlns="http://www.springframework.org/schema/beans"    xsi:schemaLocation="http://www.springframework.org/schema/beans    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">    <!-- 将PersonService类部署成Spring容器中的Bean  -->    <bean id="personService" class="PersonService">        <property name="name" value="wawa"/>    </bean></beans>

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



6运行StringTest.java,显示结果



程序结果正常运行出来。

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


0 0
原创粉丝点击