2010-03-30 38 views

回答

5

轉到春天home page和下載春季(在這裏,我使用2.5.X版本)

安裝完成後,把下面的罐子在classpath

<SPRING_HOME> /dist/spring.jar

這裏去一個bean

package br.com.introducing.Hello; 

public class Hello { 

    private String message; 

    // getter's and setter's 

} 

...

寫一個XML來配置你的bean如下

// app.xml 
<?xml version="1.0" encoding="UTF-8"?> 
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd"> 
    <bean id="hello" class="br.com.introducing.Hello"> 
     <property name="message" value="What do you want ?"/> 
    </bean> 
</beans> 

把你的app.xml的根類路徑

而且你PSVM

public static void main(String [] args) { 
    ApplicationContext appContext = new ClassPathXmlApplicationContext("app.xml"); 

    Hello hello = (Hello) appContext.getBean("hello"); 

    hello.getMessage(); // outputs What do you want ? 
} 

UPDATE

什麼是th e角色的應用程序Context.xml

當使用getBean方法時,它的行爲類似於Factory模式。喜歡的東西

public class ApplicationContext { 

    Map wiredBeans = new HashMap(); 

    public static Object getBean(String beanName) { 
     return wiredBeans.get(beanName); 
    } 

} 

正如在行動書

它是一個通用的工廠說由Spring,創建和dipensing多種類型的bean。

但是,還有更多的

  • 允許您加載文件
  • 您可以發佈事件
  • 它支持國際化(i18n的代表國際)

假設這裏有雲的消息.properties(類路徑的根)

// messages.properties 

messsageCode=What do you want ? 

要啓用國際化,你必須定義一個bean叫爲messageSource得到利用我們的資源,如下

<?xml version="1.0" encoding="UTF-8"?> 
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd"> 
    <bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource"> 
     <property name="basename" value="messages"/> 
    </bean> 
</beans> 

現在,你通常可以使用它

appContext.getMessage("messsageCode", null, null); // outputs What do you want ? 

,我們做不需要在xml文件中定義我們所有的bean。您可以使用標註(使組件掃描需要額外的設置),而不是XML,像

package br.com.introducing.Hello; 

@Component 
public class Hello { 

    private String message; 

    // getter's and setter's 

} 

組件註釋說:

春天,我是它可以通過檢索通用豆應用程序上下文

關於Spring一個很好的資源是在行動書Spring或Spring documentation

建議:仔細閱讀

+0

applicationContext.xml在spring中的作用是什麼? – saloni 2010-03-30 06:32:50

+0

@saloni添加到最原始的答案 – 2010-03-30 11:28:49

0

您也可以使用Maven創建和管理項目。您可以瞭解Maven以及如何從here

創建一個目錄結構將由Maven創建,並且您的項目目錄中將會有一個pom.xml。你可以在這個文件中提到所有的依賴關係。例如:使用Spring,你可以提到的依賴如下,

<dependency> 
<groupId>org.springframework</groupId> 
<artifactId>spring-core</artifactId> 
<version>2.5.3</version> 
</dependency> 

如果您使用的是Eclipse IDE作爲,你需要執行下面的命令,

mvn eclipse:eclipse 

這將創建一個的.project文件。您現在可以將項目導入Eclipse IDE並開始編寫您的應用程序。

對於初學者來說,春季的參考文檔和書籍像春天在行動和春季食譜是非常有用的