English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
ここでは、eclipse IDEを使用してspringフレームワークの簡単なアプリケーションを作成します。eclipse IDEでspringアプリケーションを作成する簡単な手順を見てみましょう。
Javaプロジェクトを作成します spring jarファイルを追加します クラスを作成します 値を提供するためにxmlファイルを作成します テストクラスを作成します
以下の手順で最初のspringアプリケーションを作成する方法を見てみましょう。5ステップ: eclipse IDE。
移動先 ファイルメニュー- 新規作成- プロジェクト- Javaプロジェクトプロジェクト名を入力します。例えば、firstspring- 完了現在、Javaプロジェクトが作成されました。
このアプリケーションを実行するには、主に3つの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ファイルを選択します- 完了。。
この場合、name属性を持つStudentクラスを作成しています。学生の名前はXMLファイルで提供されます。これは単なるサンプルであり、springの実際の使用法ではありません。実際の使用法は「依存注入」の章で見ることができます。Javaクラスを作成するには、 srcに右クリック - 新規作成- クラス- クラス名を書きます、例えば学生- 完了。以下のコードを書きます:
package com.w3codebox; 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およびsetterメソッドを持っています。このクラスには、displayInfo()という名前の追加メソッドがあり、该方法は挨拶メッセージを印字して学生の名前を表示します。
srcをクリックしてxmlファイルを作成します-新規作成-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.w3codebox.Student"> <property name="name" value="Vimal Jaiswal"></property> </bean> </beans>
bean 要素は、指定されたクラスにbeanを定義するために使用されます。beanの property 子要素は、nameという名前のStudentクラスの属性を指定します。属性要素で指定された値は、IOCコンテナがStudentクラスのオブジェクトに設定します。
Javaクラスを作成します、例えばテストです。ここでは、BeanFactoryのgetBean()メソッドを使用してIOCコンテナからStudentクラスのオブジェクトを取得します。テストクラスのコードを見てみましょう。
package com.w3codebox; 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(); } }
このクラスを実行すると、出力Hello: Vimal Jaiswalが得られます。