在.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。
{
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可以存取到的目录中):
<! 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 >
最后的主程序:
{
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#中的简洁,呵呵。