在.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#中的簡潔,呵呵。