服务热线:13616026886

技术文档 欢迎使用技术文档,我们为你提供从新手到专业开发者的所有资源,你也可以通过它日益精进

位置:首页 > 技术文档 > JAVA > 新手入门 > 基础入门 > 查看文档

java -- 在eclipse上使用spring

在.net上用的vs.net+spring.net+nhibernate,到了java平台上,自然对应着eclipse+spring+hibernate。上一篇文章介绍了如何在eclipse上使用hibernate的入门,本文就简单介绍一下如何在eclipse使用spring。

(1)首先,是下载spring,可以从sourceforge上下载,http://sourceforge.net/projects/springframework。目前的最新的可以下载 spring-framework-1.2.8-with-dependencies.zip 。

(2)然后,可以将spring引入到你的项目中。
先将spring-framework-1.2.8-with-dependencies.zip解压,将其中的spring.jar(dist目录中)、commons-logging.jar(lib/jakarta-commons目录)、log4j-1.2.13.jar(lib/log4j目录)这三个文件复制到的”d:/java/spring/lib" 目录中,然后在eclipse中建立一个“spring”库,将那三个文件添加进“spring”库中。

(3)测试一下:
新建两个类,student和book。

public class book...{private int id = 0 ;private string bookname ;public string getbookname() ...{return bookname;}public void setbookname(string bookname) ...{this.bookname = bookname;}public int getid() ...{return id;}public void setid(int id) ...{this.id = id;}}public class student...{private int age = 0;private string name ;private book book ;public int getage() ...{return age;}public void setage(int age) ...{this.age = age;}public string getname() ...{return name;}public void setname(string name) ...{this.name = name;}public book getbook() ...{return book;}public void setbook(book book) ...{this.book = book;}public string getbookname()...{return this.book.getbookname() ;}}

然后添加spring配置文件bean.xml(bean.xml必须在classpath可以存取到的目录中):

<?xml version="1.0" encoding="utf-8"?><!doctype beans public "-//spring/dtd bean/en""http://www.springframework.org/dtd/spring-beans.dtd"><beans><bean id="student" class="com.springtest.student"><property name="age"><value>22</value></property><property name="name"><value>sky</value></property><property name="book" ref="book"></property></bean><bean id="book" class="com.springtest.book"><property name="id"><value>1000</value></property><property name="bookname"><value>战争与和平</value></property></bean></beans>

最后的主程序:

public static void main(string[] args)...{resource res = new classpathresource("bean.xml");beanfactory factory = new xmlbeanfactory(res);student stu = (student) factory.getbean("student");system.out.println(stu.getbookname());}

运行后可以看到控制台输出--“战争与和平”。

与spring.net的使用基本完全一致(包括配置文件、beanfactory的获取等),所以熟悉spring.net的你过渡到spring是非常平滑的。
最后,java中的属性实在是没有c#中的简洁,呵呵。

扫描关注微信公众号