java實戰(七)--------myeclipse構建Spring的開發環境 spring架構配置

來源:互聯網
上載者:User

   要進行基於Spring的功能開發,就需要添加Spring的開發支援環境。所謂的Spring支援環境,就是在Java Web應用中添加Spring所需要的JAR、TLD、XML檔案,有了這些檔案我們就可以開發Spring相關的功能代碼了。


本文有兩個內容:

1.Spring環境構建

2.Spring使用----測試範例


1.Spring環境構建

構建步驟如下:

對著項目工程右鍵選擇myeclipse-----Add Spring Capabilities

A




可以對相應的類庫進行選擇


以及路徑的配置


在配置完成後,單擊"完成"按鈕即可完成Spring支援環境的添加。



2.Spring使用----測試範例


2.1 在applicationContext.xml中添加Bean配置


首先在applicationContext.xml中添加如程式2.1所示的Bean配置元素。


程式2.1  applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?><beansxmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:p="http://www.springframework.org/schema/p"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"><bean id="HelloWorld" class="Test.HelloWorld"><property name="message"><value>World</value></property></bean>

這裡我們配置了一個ID為"HelloWorld"的Bean對象,所使用的類為Test.HelloWorld,並且為該類的屬性"message"設定了一個注入的值"World"。這是<bean>元素的一種最常用的配置形式。


2.2  建立Bean類--HelloWorld.java


下面建立Bean類Test.HelloWorld.java。根據以上XML檔案配置,該類需要包含一個屬性message,因此添加一個String類型的變數message,並添加getter/setter的函數,然後添加一個測試函數execute()用以輸出被注入的參數變數message,如程式2.2所示。


程式2.2  HelloWorld.java

package Test;public class HelloWorld {    protected String message;    public String getMessage() {return message;}    public void setMessage(String message) {this.message = message;}    public void execute() {System.out.println("Hello " + getMessage() + "!");}}


2.3  運行測試類別Test.java

然後,編寫測試類別Test.java。使用FileSystemXmlApplicationContext來讀取XML設定檔applicationContext,即會返回ApplicationContext類型的變數ctx。然後使用ctx的getBean()函數取得配置的Bean對象"HelloWorld",該名稱是XML檔案中配置的Bean名稱。取得的對象經過強制類型轉換變為HelloWorld類型,將其命名為hello,並調用hello的execute()執行輸出。實現的完整代碼如程式2.3所示。



程式2.3 測試類別Test.java

package Test;import org.springframework.context.ApplicationContext;import org.springframework.context.support.FileSystemXmlApplicationContext;public class springTest {public static void main(String[] args) {ApplicationContext ctx = new FileSystemXmlApplicationContext("src/applicationContext.xml");HelloWorld hello = (HelloWorld) ctx.getBean("HelloWorld");hello.execute();}}

運行該程式,如果輸出"Hello World"則表示環境已經支援Spring了。



如果出現"java.io.FileNotFoundException: WebRoot/WEB-INF/applicationContext.xml"異常,則說明applicationContext.xml資源檔放置的路徑不對,該路徑需要是相對於當前項目demo的路徑。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.