spring 創(chuàng)建應用

在這里,我們將使用eclipse IDE創(chuàng)建一個spring框架的簡單應用程序。讓我們看看在Eclipse IDE中創(chuàng)建spring應用程序的簡單步驟。

創(chuàng)建Java項目 添加spring jar文件 創(chuàng)建類 創(chuàng)建xml文件以提供值 創(chuàng)建測試類


在Eclipse IDE中創(chuàng)建spring應用程序的步驟

讓我們看一下使用以下步驟創(chuàng)建第一個spring應用程序的5個步驟: eclipse IDE。

1、創(chuàng)建Java項目

轉到 文件菜單- 新建- 項目- Java項目。輸入項目名稱,例如firstspring- 完成。現(xiàn)在,創(chuàng)建了Java項目。

2、添加spring jar文件

運行該應用程序主要需要三個jar文件。

org.springframework.core-3.0.1.RELEASE-A com.springsource.org.apache.commons.logging-1.1.1 org.springframework.beans-3.0.1.RELEASE-A

為了將來使用,您可以下載spring核心應用程序所需的jar文件。

下載Spring的核心jar文件

全部下載Spring的jar文件,包括aop,mvc,j2ee,remoting,oxm等。

要運行此示例,您只需加載spring核心jar文件。

要在Eclipse IDE中加載jar文件, 右鍵單擊您的項目- 構建路徑- 添加外部檔案文件- 選擇所有必需的文件jar文件- 完成。。

3、創(chuàng)建Java類

在這種情況下,我們只是在創(chuàng)建具有name屬性的Student類。學生的姓名將由xml文件提供。這只是一個簡單的示例,而不是spring的實際使用。我們將在"依賴注入"一章中看到實際的用法。要創(chuàng)建Java類,請 右鍵單擊src - 新建- - 寫類名稱,例如學生- 完成。編寫以下代碼:

package com.nhooo;
public class Student {
private String name;
public String getName() {
    return name;
}
public void setName(String name) {
    this.name = name;
}
public void displayInfo(){
    System.out.println("Hello: "+name);
}
}

這是簡單的bean類,僅包含一個帶有其getter和setters方法的屬性名稱。此類包含一個名為displayInfo()的附加方法,該方法通過問候消息打印學生姓名。

4、創(chuàng)建xml文件

創(chuàng)建xml文件單擊src-新建-file-給出文件名,例如applicationContext.xml-完成。打開applicationContext.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"
    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="studentbean" class="com.nhooo.Student">
<property name="name" value="Vimal Jaiswal"></property>
</bean>
</beans>

bean 元素用于為給定類定義bean。 bean的 property 子元素指定名為name的Student類的屬性。屬性元素中指定的值將由IOC容器在Student類對象中設置。

5、創(chuàng)建測試類

創(chuàng)建Java類,例如測試。在這里,我們使用BeanFactory的getBean()方法從IOC容器中獲取Student類的對象。讓我們看一下測試類的代碼。

package com.nhooo;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
public class Test {
public static void main(String[] args) {
    Resource resource=new ClassPathResource("applicationContext.xml");
    BeanFactory factory=new XmlBeanFactory(resource);
    
    Student student=(Student)factory.getBean("studentbean");
    student.displayInfo();
}
}

現(xiàn)在運行此類。您將得到輸出Hello: Vimal Jaiswal。

spring with eclipse IDE

丰满人妻一级特黄a大片,午夜无码免费福利一级,欧美亚洲精品在线,国产婷婷成人久久Av免费高清