Spring-quick-guide

提供:Dev Guides
移動先:案内検索

Spring Framework-概要

Springは、エンタープライズJava用の最も一般的なアプリケーション開発フレームワークです。 世界中の何百万人もの開発者がSpring Frameworkを使用して、パフォーマンスが高く、テストが容易で再利用可能なコードを作成しています。

Springフレームワークは、オープンソースのJavaプラットフォームです。 最初にロッドジョンソンによって書かれ、2003年6月にApache 2.0ライセンスで最初にリリースされました。

Springはサイズと透明度に関しては軽量です。 Springフレームワークの基本バージョンは約2MBです。

Spring Frameworkのコア機能はJavaアプリケーションの開発に使用できますが、Java EEプラットフォーム上にWebアプリケーションを構築するための拡張機能があります。 Springフレームワークは、J2EE開発を使いやすくすることを目的としており、POJOベースのプログラミングモデルを有効にすることで優れたプログラミングプラクティスを促進します。

Spring Frameworkを使用する利点

以下は、Spring Frameworkを使用することの大きな利点のいくつかのリストです-

  • Springを使用すると、開発者はPOJOを使用してエンタープライズクラスのアプリケーションを開発できます。 POJOのみを使用する利点は、アプリケーションサーバーなどのEJBコンテナー製品は必要ないが、Tomcatや一部の商用製品などの堅牢なサーブレットコンテナーのみを使用するオプションがあることです。
  • 春はモジュール式に構成されています。 パッケージとクラスの数は膨大ですが、必要なものだけを心配し、残りは無視する必要があります。
  • Springは車輪を再発明するのではなく、いくつかのORMフレームワーク、ロギングフレームワーク、JEE、Quartz、JDKタイマー、およびその他のビューテクノロジーなどの既存のテクノロジーを真に活用します。
  • 環境依存コードがこのフレームワークに移動されるため、Springで記述されたアプリケーションのテストは簡単です。 さらに、JavaBeanstyle POJOを使用することにより、テストデータの注入に依存性注入を使用することが容易になります。
  • SpringのWebフレームワークは、適切に設計されたWeb MVCフレームワークであり、StrutsなどのWebフレームワークや、過剰に設計されたWebフレームワーク、またはあまり人気のないWebフレームワークの優れた代替手段となります。
  • Springは、技術固有の例外(たとえば、JDBC、Hibernate、またはJDOによってスローされる)を一貫した未チェックの例外に変換する便利なAPIを提供します。
  • 軽量のIoCコンテナーは、特にEJBコンテナーなどと比較した場合、特に軽量になる傾向があります。 これは、メモリとCPUリソースが限られているコンピューターでアプリケーションを開発および展開するのに役立ちます。
  • Springは、ローカルトランザクション(たとえば、単一のデータベースを使用)にスケールダウンし、グローバルトランザクション(たとえば、JTAを使用)にスケールアップできる一貫したトランザクション管理インターフェイスを提供します。

依存性注入(DI)

Springで最も特定されているテクノロジーは、Inversion of Controlの* Dependency Injection(DI)*フレーバーです。 * Inversion of Control(IoC)*は一般的な概念であり、さまざまな方法で表現できます。 依存性注入は、Inversion of Controlの具体例の1つ​​にすぎません。

複雑なJavaアプリケーションを記述する場合、アプリケーションクラスは他のJavaクラスから可能な限り独立している必要があります。これにより、これらのクラスを再利用し、ユニットテスト中に他のクラスとは独立してテストできるようになります。 依存性注入は、これらのクラスを結合し、同時にそれらを独立した状態に保つのに役立ちます。

依存性注入とは何ですか? これら2つの単語を別々に見てみましょう。 ここでは、依存関係部分は2つのクラス間の関連付けに変換されます。 たとえば、クラスAはクラスBに依存しています。 次に、2番目の部分であるインジェクションを見てみましょう。 つまり、クラスBはIoCによってクラスAに注入されます。

依存性注入は、コンストラクターにパラメーターを渡す方法で、またはセッターメソッドを使用して構築後に行うことができます。 依存性注入はSpring Frameworkの心臓部であるため、この概念を別の章で関連する例とともに説明します。

アスペクト指向プログラミング(AOP)

Springの主要コンポーネントの1つは、* Aspect Oriented Programming(AOP)*フレームワークです。 アプリケーションの複数のポイントにまたがる機能は「横断的関心事」と呼ばれ、これらの横断的関心事は概念的にはアプリケーションのビジネスロジックから分離されています。 ロギング、宣言的トランザクション、セキュリティ、キャッシングなどを含むさまざまな一般的な良い例があります。

OOPのモジュール性の重要な単位はクラスですが、AOPのモジュール性の単位は側面です。 DIは、アプリケーションオブジェクトを相互に分離するのに役立ちますが、AOPは、影響を受けるオブジェクトから横断的な関心事を分離するのに役立ちます。

Spring FrameworkのAOPモジュールは、アスペクト指向のプログラミング実装を提供し、メソッドインターセプターとポイントカットを定義して、分離すべき機能を実装するコードを明確に分離できます。 Spring AOPの概念については、別の章で詳しく説明します。

Spring Framework-アーキテクチャ

Springは、すべてのエンタープライズアプリケーションのワンストップショップになる可能性があります。 ただし、Springはモジュール式であるため、残りを持ち込むことなく、どのモジュールを自分に適用できるかを選択できます。 次のセクションでは、Spring Frameworkで使用可能なすべてのモジュールについて詳しく説明します。

Spring Frameworkは、アプリケーションの要件に基づいて使用できる約20のモジュールを提供します。

Spring Framework Architecture

コアコンテナ

コアコンテナは、コア、Bean、コンテキスト、および式言語モジュールで構成され、その詳細は次のとおりです-

  • Core モジュールは、IoCおよびDependency Injection機能を含むフレームワークの基本的な部分を提供します。
  • Bean モジュールは、FactoryFactoryの洗練された実装であるBeanFactoryを提供します。
  • Context モジュールは、CoreおよびBeansモジュールによって提供される強固な基盤の上に構築され、定義および設定されたオブジェクトにアクセスするための媒体です。 ApplicationContextインターフェースは、Contextモジュールの中心です。
  • SpEL モジュールは、実行時にオブジェクトグラフを照会および操作するための強力な式言語を提供します。

データアクセス/統合

データアクセス/統合層は、JDBC、ORM、OXM、JMS、およびトランザクションモジュールで構成され、その詳細は次のとおりです-

  • JDBC モジュールは、面倒なJDBC関連のコーディングを不要にするJDBC抽象化レイヤーを提供します。
  • ORM モジュールは、JPA、JDO、Hibernate、iBatisなどの一般的なオブジェクトリレーショナルマッピングAPIの統合レイヤーを提供します。
  • OXM モジュールは、JAXB、Castor、XMLBean、JiBX、およびXStreamのオブジェクト/XMLマッピング実装をサポートする抽象化レイヤーを提供します。 Java Messaging Service JMS *モジュールには、メッセージを生成および消費するための機能が含まれています。
  • Transaction モジュールは、特別なインターフェイスを実装するクラスおよびすべてのPOJOのプログラムおよび宣言トランザクション管理をサポートします。

Web

Web層は、Web、Web-MVC、Web-Socket、およびWeb-Portletモジュールで構成され、その詳細は次のとおりです-

  • Web モジュールは、マルチパートファイルアップロード機能や、サーブレットリスナーとWeb指向のアプリケーションコンテキストを使用したIoCコンテナの初期化など、基本的なWeb指向の統合機能を提供します。
  • Web-MVC モジュールには、Webアプリケーション用のSpringのModel-View-Controller(MVC)実装が含まれています。
  • Web-Socket モジュールは、Webアプリケーションでのクライアントとサーバー間のWebSocketベースの双方向通信をサポートします。
  • Web-Portlet モジュールは、ポートレット環境で使用されるMVC実装を提供し、Web-Servletモジュールの機能をミラーリングします。

その他

AOP、アスペクト、インストルメンテーション、Web、テストモジュールなど、その他の重要なモジュールはほとんどありません。詳細は次のとおりです-

  • AOP モジュールは、アスペクト指向のプログラミング実装を提供し、メソッドインターセプターとポイントカットを定義して、分離すべき機能を実装するコードを明確に分離できます。
  • Aspects モジュールは、AspectJとの統合を提供します。AspectJは強力で成熟したAOPフレームワークです。
  • Instrumentation モジュールは、特定のアプリケーションサーバーで使用されるクラスインストルメンテーションサポートとクラスローダー実装を提供します。
  • Messaging モジュールは、アプリケーションで使用するWebSocketサブプロトコルとしてSTOMPのサポートを提供します。 また、WebSocketクライアントからのSTOMPメッセージをルーティングおよび処理するための注釈プログラミングモデルもサポートしています。
  • Test モジュールは、JUnitまたはTestNGフレームワークを使用したSpringコンポーネントのテストをサポートします。

Spring-環境設定

この章では、Spring Frameworkで作業を開始するための開発環境を準備する方法について説明します。 また、Spring Frameworkをセットアップする前に、マシン上でJDK、Tomcat、Eclipseをセットアップする方法についても説明します-

ステップ1-Java Development Kit(JDK)のセットアップ

OracleのJavaサイトから最新バージョンのSDKをダウンロードできます-https://www.oracle.com/technetwork/java/javase/downloads/indexl[Java SE Downloads。]ダウンロードしたファイルにJDKをインストールする手順は、次のとおりです。セットアップをインストールおよび構成するための所定の手順。 最後に、PATHおよびJAVA_HOME環境変数を設定して、javaおよびjavacを含むディレクトリ(通常はそれぞれjava_install_dir/binおよびjava_install_dir)を参照します。

Windowsを実行していて、JDKをC:\ jdk1.6.0_15にインストールした場合、C:\ autoexec.batファイルに次の行を追加する必要があります。

set PATH=C:\jdk1.6.0_15\bin;%PATH%
set JAVA_HOME=C:\jdk1.6.0_15

または、Windows NT/2000/XPでは、[マイコンピュータ]を右クリックして、[プロパティ]→[詳細]→[環境変数]を選択する必要があります。 次に、PATH値を更新し、[OK]ボタンをクリックする必要があります。

Unix(Solaris、Linuxなど)で、SDKが/usr/local/jdk1.6.0_15にインストールされ、Cシェルを使用する場合、次を.cshrcファイルに追加する必要があります。

setenv PATH/usr/local/jdk1.6.0_15/bin:$PATH
setenv JAVA_HOME/usr/local/jdk1.6.0_15

あるいは、Borland JBuilder、Eclipse、IntelliJ IDEA、またはSun ONE Studioなどの統合開発環境(IDE)を使用する場合、Javaをインストールした場所をIDEが認識していることを確認するために、簡単なプログラムをコンパイルおよび実行する必要があります。 それ以外の場合は、IDEのドキュメントに記載されている適切なセットアップを実行する必要があります。

ステップ2-Apache Common Logging APIのインストール

Apache Commons Logging APIの最新バージョンは、https://commons.apache.org/logging/download_logging.cgi [https://commons.apache.org/logging/]からダウンロードできます。 インストールをダウンロードしたら、バイナリ配布物を便利な場所に解凍します。 たとえば、WindowsのC:\ commons-logging-1.1.1、またはLinux/Unixの/usr/local/commons-logging-1.1.1にあります。 このディレクトリには、次のjarファイルやその他のサポートドキュメントなどが含まれます。

Common Logging API

このディレクトリでCLASSPATH変数を適切に設定してください。そうしないと、アプリケーションの実行中に問題が発生します。

ステップ3-Eclipse IDEのセットアップ

このチュートリアルのすべての例は、Eclipse IDEを使用して作成されています。 そのため、マシンにEclipseの最新バージョンをインストールすることをお勧めします。

Eclipse IDEをインストールするには、https://www.eclipse.org/downloads/から最新のEclipseバイナリをダウンロードします。 インストールをダウンロードしたら、バイナリ配布物を便利な場所に解凍します。 たとえば、WindowsのC:\ eclipse、またはLinux/Unixの/usr/local/eclipseで、最後にPATH変数を適切に設定します。

Eclipseは、Windowsマシンで次のコマンドを実行することで開始できます。または、eclipse.exeをダブルクリックするだけで開始できます

%C:\eclipse\eclipse.exe

Eclipseは、Unix(Solaris、Linuxなど)マシンで次のコマンドを実行することで起動できます-

$/usr/local/eclipse/eclipse

正常に起動した後、すべてが正常であれば、次の結果が表示されます-

Eclipseホームページ

ステップ4-Spring Frameworkライブラリのセットアップ

これで問題がなければ、Springフレームワークのセットアップに進むことができます。 以下は、フレームワークをダウンロードしてマシンにインストールする簡単な手順です。

  • SpringをWindowsにインストールするかUnixにインストールするかを選択してから、次のステップに進み、Windowsの場合は.zipファイルを、Unixの場合は.tzファイルをダウンロードします。
  • [[1]]
  • このチュートリアルの開発時に、 spring-framework-4.1.6.RELEASE-dist.zip がWindowsマシンにダウンロードされました。 ダウンロードしたファイルを解凍すると、E:\ spring内に次のディレクトリ構造が作成されます。

春のディレクトリ

すべてのSpringライブラリは、ディレクトリ E:\ spring \ libs にあります。 このディレクトリでCLASSPATH変数を適切に設定してください。そうしないと、アプリケーションの実行中に問題が発生します。 Eclipseを使用している場合、すべての設定はEclipseを介して行われるため、CLASSPATHを設定する必要はありません。

この最後の手順が完了したら、次の章の最初のSpringの例に進む準備ができています。

春-Hello Worldの例

Spring Frameworkで実際のプログラミングを始めましょう。 Springフレームワークを使用して最初の例の記述を開始する前に、リンク:/spring/spring_environment_setup [Spring-Environment Setup]の章で説明されているように、Spring環境が適切にセットアップされていることを確認する必要があります。 また、Eclipse IDEの実用的な知識があることも前提としています。

ここで、「Hello World!」を出力する単純なSpringアプリケーションの作成に進みましょう。または、Spring Bean構成ファイルで行われた構成に基づいたその他のメッセージ。

ステップ1-Javaプロジェクトの作成

最初のステップは、Eclipse IDEを使用して簡単なJavaプロジェクトを作成することです。 ファイル→新規→プロジェクト*オプションに従い、最後にウィザードリストから Javaプロジェクト*ウィザードを選択します。 次のようにウィザードウィンドウを使用して、プロジェクトに HelloSpring という名前を付けます-

Hello Spring Wizard

プロジェクトが正常に作成されると、 Project Explorer に次のコンテンツが表示されます-

Hello Springディレクトリ

ステップ2-必要なライブラリを追加する

2番目のステップとして、プロジェクトにSpring Frameworkと共通のロギングAPIライブラリを追加します。 これを行うには、プロジェクト名 HelloSpring を右クリックし、コンテキストメニューで使用可能な次のオプションに従います。

Javaビルドパス

*Libraries* タブにある *Add External JARs* ボタンを使用して、Spring FrameworkおよびCommon Loggingインストールディレクトリから次のコアJARを追加します-
  • commons-logging-1.1.1
  • spring-aop-4.1.6.RELEASE
  • spring-aspects-4.1.6.RELEASE
  • spring-beans-4.1.6.RELEASE
  • spring-context-4.1.6.RELEASE
  • spring-context-support-4.1.6.RELEASE
  • spring-core-4.1.6.RELEASE
  • spring-expression-4.1.6.RELEASE
  • spring-instrument-4.1.6.RELEASE
  • spring-instrument-tomcat-4.1.6.RELEASE
  • spring-jdbc-4.1.6.RELEASE
  • spring-jms-4.1.6.RELEASE
  • spring-messaging-4.1.6.RELEASE
  • spring-orm-4.1.6.RELEASE
  • spring-oxm-4.1.6.RELEASE
  • spring-test-4.1.6.RELEASE
  • spring-tx-4.1.6.RELEASE
  • spring-web-4.1.6.RELEASE
  • spring-webmvc-4.1.6.RELEASE
  • spring-webmvc-portlet-4.1.6.RELEASE
  • spring-websocket-4.1.6.RELEASE

手順3-ソースファイルの作成

*HelloSpring* プロジェクトの下に実際のソースファイルを作成しましょう。 まず、 *com.finddevguides* というパッケージを作成する必要があります。 これを行うには、パッケージエクスプローラーセクションで *src* を右クリックし、オプション-*新規→パッケージ*に従います。

次に、com.finddevguidesパッケージの下に HelloWorld.java および MainApp.java ファイルを作成します。

Spring Source Files

*HelloWorld.java* ファイルの内容は次のとおりです-
package com.finddevguides;

public class HelloWorld {
   private String message;

   public void setMessage(String message){
      this.message  = message;
   }
   public void getMessage(){
      System.out.println("Your Message : " + message);
   }
}

以下は、2番目のファイル MainApp.java の内容です-

package com.finddevguides;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MainApp {
   public static void main(String[] args) {
      ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml");
      HelloWorld obj = (HelloWorld) context.getBean("helloWorld");
      obj.getMessage();
   }
}

次の2つの重要な点は、メインプログラムについて注意することです-

 *最初のステップは、フレームワークAPI* ClassPathXmlApplicationContext()*を使用したアプリケーションコンテキストを作成することです。 このAPIはBean構成ファイルをロードし、最終的に提供されたAPIに基づいて、すべてのオブジェクトの作成と初期化を行います。 構成ファイルに記載されているBean。
* 2番目のステップは、作成されたコンテキストの* getBean()*メソッドを使用して必要なBeanを取得するために使用されます。 このメソッドはBean IDを使用して、最終的に実際のオブジェクトにキャストできる汎用オブジェクトを返します。 オブジェクトを取得したら、このオブジェクトを使用して任意のクラスメソッドを呼び出すことができます。

ステップ4-Bean構成ファイルの作成

XMLファイルであり、Beanを接着するセメントとして機能するBean設定ファイルを作成する必要があります。 クラスを一緒に。 このファイルは、次のスクリーンショットに示すように src ディレクトリの下に作成する必要があります-

Bean設定ファイル

通常、開発者はこのファイルに Beans.xml という名前を付けますが、好きな名前を自由に選択できます。 このファイルがCLASSPATHで使用可能であることを確認し、MainApp.javaファイルに示されているアプリケーションコンテキストの作成中にメインアプリケーションで同じ名前を使用する必要があります。

Beans.xmlは、一意のIDを異なるBeanに割り当て、Springソースファイルに影響を与えることなく異なる値を持つオブジェクトの作成を制御するために使用されます。 たとえば、次のファイルを使用すると、「message」変数に任意の値を渡すことができ、HelloWorld.javaおよびMainApp.javaファイルに影響を与えることなく、メッセージの異なる値を印刷できます。 それがどのように機能するか見てみましょう-

<?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-3.0.xsd">

   <bean id = "helloWorld" class = "com.finddevguides.HelloWorld">
      <property name = "message" value = "Hello World!"/>
   </bean>

</beans>

Springアプリケーションがメモリにロードされると、Frameworkは上記の構成ファイルを使用して定義されたすべてのBeanを作成し、 <bean> タグで定義された一意のIDを割り当てます。 <property> タグを使用して、オブジェクト作成時に使用されるさまざまな変数の値を渡すことができます。

ステップ5-プログラムの実行

ソースおよびBean構成ファイルの作成が完了したら、プログラムをコンパイルおよび実行するこのステップの準備が整います。 これを行うには、MainApp.Javaファイルタブをアクティブのままにして、Eclipse IDEで使用可能な*実行*オプションを使用するか、 Ctrl + F11 を使用して MainApp アプリケーションをコンパイルおよび実行します。 すべてがアプリケーションで問題ない場合、Eclipse IDEのコンソールに次のメッセージが出力されます-

Your Message : Hello World!

おめでとうございます、最初のSpringアプリケーションが正常に作成されました。 「message」プロパティの値を変更し、両方のソースファイルを変更しないことで、上記のSpringアプリケーションの柔軟性を確認できます。

春-IoCコンテナー

Springコンテナは、Spring Frameworkの中核です。 コンテナはオブジェクトを作成し、それらを結び付け、構成し、作成から破棄までのライフサイクル全体を管理します。 SpringコンテナはDIを使用して、アプリケーションを構成するコンポーネントを管理します。 これらのオブジェクトは、Spring Beanと呼ばれます。これについては、次の章で説明します。

コンテナは、提供された構成メタデータを読み取ることにより、どのオブジェクトをインスタンス化、構成、およびアセンブルするかの指示を取得します。 構成メタデータは、XML、Java注釈、またはJavaコードのいずれかで表すことができます。 次の図は、Springの仕組みの概要を示しています。 Spring IoCコンテナは、Java POJOクラスと構成メタデータを使用して、完全に構成された実行可能なシステムまたはアプリケーションを生成します。

Spring IoC Container

Springは、次の2つの異なるタイプのコンテナーを提供します。

Sr.No. Container & Description
1

Spring BeanFactory Container

これは、DIの基本的なサポートを提供する最も単純なコンテナーであり、_org.springframework.beans.factory.BeanFactory_インターフェースによって定義されます。 BeanFactoryおよび関連するインターフェース(BeanFactoryAware、InitializingBean、DisposableBeanなど)は、Springと統合する多数のサードパーティフレームワークとの下位互換性を目的として、Springに引き続き存在します。

2

Spring ApplicationContext Container

このコンテナは、プロパティファイルからテキストメッセージを解決する機能や、関心のあるイベントリスナーにアプリケーションイベントを発行する機能など、エンタープライズ固有の機能を追加します。 このコンテナは、_org.springframework.context.ApplicationContext_インターフェースによって定義されます。

_ApplicationContext_コンテナにはBeanFactorycontainerのすべての機能が含まれているため、通常は_BeanFactory_よりもお勧めです。 BeanFactoryは、データ量と速度が重要なモバイルデバイスやアプレットベースのアプリケーションなどの軽量アプリケーションに引き続き使用できます。

春-Beanの定義

アプリケーションのバックボーンを形成し、Spring IoCコンテナによって管理されるオブジェクトは beans と呼ばれます。 Beanは、Spring IoCコンテナーによってインスタンス化、アセンブル、または管理されるオブジェクトです。 これらのBeanは、コンテナに提供する構成メタデータを使用して作成されます。 たとえば、前の章ですでに見たXML <bean/>定義の形式。

Beanの定義には、コンテナが次のことを知るために必要な*構成メタデータ*と呼ばれる情報が含まれています-

  • Beanの作成方法
  • Beanのライフサイクルの詳細 *Beanの依存関係

上記のすべての構成メタデータは、各Bean定義を構成する次のプロパティのセットに変換されます。

Sr.No. Properties & Description
1
  • class*

この属性は必須であり、Beanの作成に使用されるBeanクラスを指定します。

2

name

この属性は、Bean識別子を一意に指定します。 XMLベースの構成メタデータでは、idまたはname属性、あるいはその両方を使用してBean識別子を指定します。

3

scope

この属性は、特定のBean定義から作成されたオブジェクトのスコープを指定します。これについては、Beanスコープの章で説明します。

4

constructor-arg

これは依存関係を注入するために使用され、以降の章で説明します。

5

properties

これは依存関係を注入するために使用され、以降の章で説明します。

6

autowiring mode

これは依存関係を注入するために使用され、以降の章で説明します。

7

lazy-initialization mode

遅延初期化Beanは、起動時ではなく、最初に要求されたときにBeanインスタンスを作成するようにIoCコンテナーに指示します。

8

initialization method

Beanに必要なすべてのプロパティがコンテナによって設定された直後に呼び出されるコールバック。 Beanライフサイクルの章で説明します。

9

destruction method

Beanを含むコンテナが破棄されるときに使用されるコールバック。 Beanライフサイクルの章で説明します。

Spring構成メタデータ

Spring IoCコンテナーは、この構成メタデータが実際に書き込まれる形式から完全に切り離されています。 以下は、Spring Containerに構成メタデータを提供する3つの重要な方法です-

  • XMLベースの構成ファイル。
  • 注釈ベースの構成
  • Javaベースの構成

コンテナにXMLベースの構成メタデータがどのように提供されるかは既に見てきましたが、遅延初期化、初期化メソッド、破棄メソッドなど、さまざまなBean定義を持つ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-3.0.xsd">

   <!-- A simple bean definition -->
   <bean id = "..." class = "...">
      <!-- collaborators and configuration for this bean go here -->
   </bean>

   <!-- A bean definition with lazy init set on -->
   <bean id = "..." class = "..." lazy-init = "true">
      <!-- collaborators and configuration for this bean go here -->
   </bean>

   <!-- A bean definition with initialization method -->
   <bean id = "..." class = "..." init-method = "...">
      <!-- collaborators and configuration for this bean go here -->
   </bean>

   <!-- A bean definition with destruction method -->
   <bean id = "..." class = "..." destroy-method = "...">
      <!-- collaborators and configuration for this bean go here -->
   </bean>

   <!-- more bean definitions go here -->

</beans>

link:/spring/spring hello world example [Spring Hello World Example]をチェックして、Spring Beanの定義、構成、作成方法を理解できます。

別の章で注釈ベースの構成について説明します。 Spring Dependency Injection with Annotationsでプログラミングを開始する前に、他のいくつかの重要なSpringの概念を把握してほしいので、別の章で意図的に説明します。

春-Beanスコープ

<bean>を定義するとき、そのbeanのスコープを宣言するオプションがあります。 たとえば、Springが必要になるたびに新しいBeanインスタンスを生成するように強制するには、Beanのスコープ属性を prototype として宣言する必要があります。 同様に、Springが必要になるたびに同じBeanインスタンスを返すようにする場合は、Beanのスコープ属性を*シングルトン*として宣言する必要があります。

Spring Frameworkは、次の5つのスコープをサポートします。そのうち3つは、Web対応のApplicationContextを使用する場合にのみ使用できます。

Sr.No. Scope & Description
1

singleton

これは、Spring IoCコンテナーごとにBean定義を単一インスタンスにスコープします(デフォルト)。

2

prototype

これにより、単一のBean定義のスコープが任意の数のオブジェクトインスタンスになります。

3

request

これにより、Bean定義がHTTP要求にスコープされます。 Web対応のSpring ApplicationContextのコンテキストでのみ有効です。

4

session

これは、Bean定義をHTTPセッションにスコープします。 Web対応のSpring ApplicationContextのコンテキストでのみ有効です。

5

global-session

これにより、Bean定義がグローバルHTTPセッションにスコープされます。 Web対応のSpring ApplicationContextのコンテキストでのみ有効です。

この章では、最初の2つのスコープについて説明し、残りの3つのスコープについては、Web対応のSpring ApplicationContextについて説明するときに説明します。

シングルトンスコープ

スコープがシングルトンに設定されている場合、Spring IoCコンテナーは、そのBean定義で定義されたオブジェクトのインスタンスを1つだけ作成します。 この単一のインスタンスは、そのようなシングルトンBeanのキャッシュに格納され、その名前付きBeanに対する後続のすべてのリクエストと参照は、キャッシュされたオブジェクトを返します。

デフォルトのスコープは常にシングルトンです。 ただし、Beanのインスタンスが1つだけ必要な場合は、次のコードスニペットに示すように、Bean構成ファイルで scope プロパティを singleton に設定できます-

<!-- A bean definition with singleton scope -->
<bean id = "..." class = "..." scope = "singleton">
   <!-- collaborators and configuration for this bean go here -->
</bean>

動作するEclipse IDEを用意し、次の手順を実行してSpringアプリケーションを作成します。

Steps Description
1 Create a project with a name SpringExample and create a package com.finddevguides under the *src *folder in the created project.
2 Add required Spring libraries using Add External JARs option as explained in the Spring Hello World Example chapter.
3 Create Java classes HelloWorld and MainApp under the com.finddevguides package.
4 Create Beans configuration file Beans.xml under the* src* folder.
5 The final step is to create the content of all the Java files and Bean Configuration file and run the application as explained below.
*HelloWorld.java* ファイルの内容は次のとおりです-
package com.finddevguides;

public class HelloWorld {
   private String message;

   public void setMessage(String message){
      this.message  = message;
   }
   public void getMessage(){
      System.out.println("Your Message : " + message);
   }
}

以下は MainApp.java ファイルの内容です-

package com.finddevguides;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MainApp {
   public static void main(String[] args) {
      ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml");
      HelloWorld objA = (HelloWorld) context.getBean("helloWorld");

      objA.setMessage("I'm object A");
      objA.getMessage();

      HelloWorld objB = (HelloWorld) context.getBean("helloWorld");
      objB.getMessage();
   }
}

以下は、シングルトンスコープに必要な構成ファイル Beans.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-3.0.xsd">

   <bean id = "helloWorld" class = "com.finddevguides.HelloWorld" scope = "singleton">
   </bean>

</beans>

ソースおよびBean構成ファイルの作成が完了したら、アプリケーションを実行しましょう。 すべてがあなたのアプリケーションでうまくいけば、それは次のメッセージを印刷します-

Your Message : I'm object A
Your Message : I'm object A

プロトタイプスコープ

スコープがプロトタイプに設定されている場合、Spring IoCコンテナーは、その特定のBeanに対する要求が行われるたびに、オブジェクトの新しいBeanインスタンスを作成します。 原則として、すべてのステートフルBeanにはプロトタイプスコープを使用し、ステートレスBeanにはシングルトンスコープを使用します。

プロトタイプスコープを定義するには、次のコードスニペットに示すように、Bean構成ファイルで scope プロパティを prototype に設定できます-

<!-- A bean definition with prototype scope -->
<bean id = "..." class = "..." scope = "prototype">
   <!-- collaborators and configuration for this bean go here -->
</bean>

作業中のEclipse IDEを用意し、次の手順に従ってSpringアプリケーションを作成します。

Steps Description
1 Create a project with a name SpringExample and create a package com.finddevguides under the *src *folder in the created project.
2 Add required Spring libraries using Add External JARs option as explained in the Spring Hello World Example chapter.
3 Create Java classes HelloWorld and MainApp under the com.finddevguides package.
4 Create Beans configuration file Beans.xml under the* src* folder.
5 The final step is to create the content of all the Java files and Bean Configuration file and run the application as explained below.
*HelloWorld.java* ファイルの内容は次のとおりです。
package com.finddevguides;

public class HelloWorld {
   private String message;

   public void setMessage(String message){
      this.message  = message;
   }
   public void getMessage(){
      System.out.println("Your Message : " + message);
   }
}

以下は MainApp.java ファイルの内容です-

package com.finddevguides;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MainApp {
   public static void main(String[] args) {
      ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml");
      HelloWorld objA = (HelloWorld) context.getBean("helloWorld");

      objA.setMessage("I'm object A");
      objA.getMessage();

      HelloWorld objB = (HelloWorld) context.getBean("helloWorld");
      objB.getMessage();
   }
}

以下は、プロトタイプスコープに必要な構成ファイル Beans.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-3.0.xsd">

   <bean id = "helloWorld" class = "com.finddevguides.HelloWorld" scope = "prototype">
   </bean>

</beans>

ソースおよびBean構成ファイルの作成が完了したら、アプリケーションを実行しましょう。 すべてがあなたのアプリケーションでうまくいけば、それは次のメッセージを印刷します-

Your Message : I'm object A
Your Message : null

春-Beanのライフサイクル

Spring Beanのライフサイクルは簡単に理解できます。 Beanがインスタンス化されるとき、使用可能な状態にするために何らかの初期化を実行する必要がある場合があります。 同様に、Beanが不要になり、コンテナから削除されると、クリーンアップが必要になる場合があります。

Beanのインスタンス化とその破棄の間に舞台裏で行われるアクティビティのリストがありますが、この章では、Beanの初期化と破棄のときに必要な2つの重要なBeanライフサイクルコールバックメソッドについてのみ説明します。

Beanのセットアップとティアダウンを定義するには、 initmethod および/または destroy-method パラメーターで<bean>を宣言するだけです。 init-method属性は、インスタンス化の直後にBeanで呼び出されるメソッドを指定します。 同様に、destroymethodは、Beanがコンテナから削除される直前に呼び出されるメソッドを指定します。

初期化コールバック

org.springframework.beans.factory.InitializingBeanインターフェイスは、単一のメソッドを指定します-

void afterPropertiesSet() throws Exception;

したがって、次のようにafterPropertiesSet()メソッド内で上記のインターフェイスと初期化作業を簡単に実装できます-

public class ExampleBean implements InitializingBean {
   public void afterPropertiesSet() {
     //do some initialization work
   }
}

XMLベースの構成メタデータの場合、 init-method 属性を使用して、引数なしの無効な署名を持つメソッドの名前を指定できます。 たとえば-

<bean id = "exampleBean" class = "examples.ExampleBean" init-method = "init"/>

以下はクラス定義です-

public class ExampleBean {
   public void init() {
     //do some initialization work
   }
}

破壊コールバック

_org.springframework.beans.factory.DisposableBean_インターフェイスは、単一のメソッドを指定します-

void destroy() throws Exception;

したがって、次のようにdestroy()メソッド内で上記のインターフェイスとファイナライズ作業を簡単に実装できます-

public class ExampleBean implements DisposableBean {
   public void destroy() {
     //do some destruction work
   }
}

XMLベースの構成メタデータの場合、 destroy-method 属性を使用して、引数のないvoidシグネチャを持つメソッドの名前を指定できます。 たとえば-

<bean id = "exampleBean" class = "examples.ExampleBean" destroy-method = "destroy"/>

以下はクラス定義です-

public class ExampleBean {
   public void destroy() {
     //do some destruction work
   }
}

非Webアプリケーション環境でSpringのIoCコンテナーを使用している場合。たとえば、リッチクライアントデスクトップ環境では、シャットダウンフックをJVMに登録します。 これにより、正常なシャットダウンが保証され、シングルトンBeanの関連するdestroyメソッドが呼び出され、すべてのリソースが解放されます。

XML構成はメソッドの命名に関して非常に柔軟性があるため、InitializingBeanまたはDisposableBeanコールバックを使用しないことをお勧めします。

動作するEclipse IDEを用意し、次の手順を実行してSpringアプリケーションを作成します。

Steps Description
1 Create a project with a name SpringExample and create a package com.finddevguides under the *src *folder in the created project.
2 Add required Spring libraries using Add External JARs option as explained in the Spring Hello World Example chapter.
3 Create Java classes HelloWorld and MainApp under the com.finddevguides package.
4 Create Beans configuration file Beans.xml under the* src* folder.
5 The final step is to create the content of all the Java files and Bean Configuration file and run the application as explained below.
*HelloWorld.java* ファイルの内容は次のとおりです-
package com.finddevguides;

public class HelloWorld {
   private String message;

   public void setMessage(String message){
      this.message = message;
   }
   public void getMessage(){
      System.out.println("Your Message : " + message);
   }
   public void init(){
      System.out.println("Bean is going through init.");
   }
   public void destroy() {
      System.out.println("Bean will destroy now.");
   }
}

以下は MainApp.java ファイルの内容です。 ここでは、AbstractApplicationContextクラスで宣言されているシャットダウンフック* registerShutdownHook()*メソッドを登録する必要があります。 これにより、正常なシャットダウンが保証され、関連する破棄メソッドが呼び出されます。

package com.finddevguides;

import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MainApp {
   public static void main(String[] args) {
      AbstractApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml");

      HelloWorld obj = (HelloWorld) context.getBean("helloWorld");
      obj.getMessage();
      context.registerShutdownHook();
   }
}

以下は、initおよびdestroyメソッドに必要な構成ファイル Beans.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-3.0.xsd">

   <bean id = "helloWorld" class = "com.finddevguides.HelloWorld" init-method = "init"
      destroy-method = "destroy">
      <property name = "message" value = "Hello World!"/>
   </bean>

</beans>

ソースおよびBean構成ファイルの作成が完了したら、アプリケーションを実行しましょう。 すべてがあなたのアプリケーションでうまくいけば、それは次のメッセージを印刷します-

Bean is going through init.
Your Message : Hello World!
Bean will destroy now.

デフォルトの初期化および破棄メソッド

同じ名前のメソッドを初期化および/または破棄するBeanが多すぎる場合、個々のBeanで init-methoddestroy-method を宣言する必要はありません。 代わりに、フレームワークは、次のように<beans>要素の default-init-method および default-destroy-method 属性を使用して、このような状況を柔軟に構成できます-

<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-3.0.xsd"
   default-init-method = "init"
   default-destroy-method = "destroy">

   <bean id = "..." class = "...">
      <!-- collaborators and configuration for this bean go here -->
   </bean>

</beans>

Spring-Beanポストプロセッサ

*BeanPostProcessor* インターフェイスは、独自のインスタンス化ロジック、依存関係解決ロジックなどを提供するために実装できるコールバックメソッドを定義します。 Springコンテナが1つ以上のBeanPostProcessor実装をプラグインして、Beanのインスタンス化、構成、および初期化を完了した後、カスタムロジックを実装することもできます。

BeanPostProcessorが Ordered インターフェースを実装している場合、 order プロパティを設定することにより、複数のBeanPostProcessorインターフェースを設定でき、これらのBeanPostProcessorインターフェースの実行順序を制御できます。

BeanPostProcessorsはBean(またはオブジェクト)インスタンスで動作します。つまり、Spring IoCコンテナーがBeanインスタンスをインスタンス化し、BeanPostProcessorインターフェースが機能します。

*ApplicationContext* は、 *BeanPostProcessor* インターフェースの実装で定義されたBeanを自動的に検出し、これらのBeanをポストプロセッサーとして登録し、Bean作成時にコンテナーによって適切に呼び出されます。

次の例は、ApplicationContextのコンテキストでBeanPostProcessorsを作成、登録、および使用する方法を示しています。

動作するEclipse IDEを用意し、次の手順を実行してSpringアプリケーションを作成します。

Steps Description
1 Create a project with a name SpringExample and create a package com.finddevguides under the *src *folder in the created project.
2 Add required Spring libraries using Add External JARs option as explained in the Spring Hello World Example chapter.
3 Create Java classes HelloWorld, InitHelloWorld and MainApp under the com.finddevguides package.
4 Create Beans configuration file Beans.xml under the* src* folder.
5 The final step is to create the content of all the Java files and Bean Configuration file and run the application as explained below.
*HelloWorld.java* ファイルの内容は次のとおりです-
package com.finddevguides;

public class HelloWorld {
   private String message;

   public void setMessage(String message){
      this.message  = message;
   }
   public void getMessage(){
      System.out.println("Your Message : " + message);
   }
   public void init(){
      System.out.println("Bean is going through init.");
   }
   public void destroy(){
      System.out.println("Bean will destroy now.");
   }
}

これは、Beanの初期化の前後にBean名を出力するBeanPostProcessorを実装する非常に基本的な例です。 両方のポストプロセッサメソッド内のBeanオブジェクトにアクセスできるため、Beanを初期化する前後に、より複雑なロジックを実装できます。

*InitHelloWorld.java* ファイルの内容は次のとおりです-
package com.finddevguides;

import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.beans.BeansException;

public class InitHelloWorld implements BeanPostProcessor {
   public Object postProcessBeforeInitialization(Object bean, String beanName)
      throws BeansException {

      System.out.println("BeforeInitialization : " + beanName);
      return bean; //you can return any other object as well
   }
   public Object postProcessAfterInitialization(Object bean, String beanName)
      throws BeansException {

      System.out.println("AfterInitialization : " + beanName);
      return bean; //you can return any other object as well
   }
}

以下は MainApp.java ファイルの内容です。 ここでは、AbstractApplicationContextクラスで宣言されているシャットダウンフック* registerShutdownHook()*メソッドを登録する必要があります。 これにより、正常なシャットダウンが保証され、関連する破棄メソッドが呼び出されます。

package com.finddevguides;

import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MainApp {
   public static void main(String[] args) {
      AbstractApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml");

      HelloWorld obj = (HelloWorld) context.getBean("helloWorld");
      obj.getMessage();
      context.registerShutdownHook();
   }
}

以下は、initおよびdestroyメソッドに必要な構成ファイル Beans.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-3.0.xsd">

   <bean id = "helloWorld" class = "com.finddevguides.HelloWorld"
      init-method = "init" destroy-method = "destroy">
      <property name = "message" value = "Hello World!"/>
   </bean>

   <bean class = "com.finddevguides.InitHelloWorld"/>

</beans>

ソースおよびBean構成ファイルの作成が完了したら、アプリケーションを実行します。 すべてがあなたのアプリケーションでうまくいけば、それは次のメッセージを印刷します-

BeforeInitialization : helloWorld
Bean is going through init.
AfterInitialization : helloWorld
Your Message : Hello World!
Bean will destroy now.

Spring-Bean定義の継承

Bean定義には、コンストラクター引数、プロパティ値、および初期化メソッド、静的ファクトリーメソッド名などのコンテナー固有の情報など、多くの構成情報を含めることができます。

子Bean定義は、親定義から構成データを継承します。 子定義は、必要に応じて一部の値をオーバーライドしたり、他の値を追加したりできます。

Spring Bean定義の継承はJavaクラスの継承とは関係ありませんが、継承の概念は同じです。 親Bean定義をテンプレートとして定義でき、他の子Beanは必要な構成を親Beanから継承できます。

XMLベースの構成メタデータを使用する場合、この属性の値として親Beanを指定して、 parent 属性を使用して、子Bean定義を示します。

動作するEclipse IDEを用意し、次の手順を実行してSpringアプリケーションを作成します。

Steps Description
1 Create a project with a name SpringExample and create a package com.finddevguides under the *src *folder in the created project.
2 Add required Spring libraries using Add External JARs option as explained in the Spring Hello World Example chapter.
3 Create Java classes HelloWorld, HelloIndia and MainApp under the com.finddevguides package.
4 Create Beans configuration file Beans.xml under the* src* folder.
5 The final step is to create the content of all the Java files and Bean Configuration file and run the application as explained below.

以下は、2つのプロパティ_message1_および_message2_を持つ「helloWorld」Beanを定義した構成ファイル Beans.xml です。 次の「helloIndia」Beanは、 parent 属性を使用して「helloWorld」Beanの子として定義されています。 子Beanは_message2_プロパティをそのまま継承し、_message1_プロパティをオーバーライドして、もう1つのプロパティ_message3_を導入します。

<?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-3.0.xsd">

   <bean id = "helloWorld" class = "com.finddevguides.HelloWorld">
      <property name = "message1" value = "Hello World!"/>
      <property name = "message2" value = "Hello Second World!"/>
   </bean>

   <bean id ="helloIndia" class = "com.finddevguides.HelloIndia" parent = "helloWorld">
      <property name = "message1" value = "Hello India!"/>
      <property name = "message3" value = "Namaste India!"/>
   </bean>
</beans>
*HelloWorld.java* ファイルの内容は次のとおりです-
package com.finddevguides;

public class HelloWorld {
   private String message1;
   private String message2;

   public void setMessage1(String message){
      this.message1 = message;
   }
   public void setMessage2(String message){
      this.message2 = message;
   }
   public void getMessage1(){
      System.out.println("World Message1 : " + message1);
   }
   public void getMessage2(){
      System.out.println("World Message2 : " + message2);
   }
}
*HelloIndia.java* ファイルの内容は次のとおりです-
package com.finddevguides;

public class HelloIndia {
   private String message1;
   private String message2;
   private String message3;

   public void setMessage1(String message){
      this.message1 = message;
   }
   public void setMessage2(String message){
      this.message2 = message;
   }
   public void setMessage3(String message){
      this.message3 = message;
   }
   public void getMessage1(){
      System.out.println("India Message1 : " + message1);
   }
   public void getMessage2(){
      System.out.println("India Message2 : " + message2);
   }
   public void getMessage3(){
      System.out.println("India Message3 : " + message3);
   }
}

以下は MainApp.java ファイルの内容です-

package com.finddevguides;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MainApp {
   public static void main(String[] args) {
      ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml");

      HelloWorld objA = (HelloWorld) context.getBean("helloWorld");
      objA.getMessage1();
      objA.getMessage2();

      HelloIndia objB = (HelloIndia) context.getBean("helloIndia");
      objB.getMessage1();
      objB.getMessage2();
      objB.getMessage3();
   }
}

ソースおよびBean構成ファイルの作成が完了したら、アプリケーションを実行しましょう。 すべてがあなたのアプリケーションでうまくいけば、それは次のメッセージを印刷します-

World Message1 : Hello World!
World Message2 : Hello Second World!
India Message1 : Hello India!
India Message2 : Hello Second World!
India Message3 : Namaste India!

ここで確認した場合、「helloIndia」Beanの作成中にmessage2を渡しませんでしたが、Bean Definition Inheritanceのために渡されました。

Bean定義テンプレート

Bean定義テンプレートを作成できます。このテンプレートは、他の子Bean定義であまり労力をかけずに使用できます。 Bean定義テンプレートを定義する際、 class 属性を指定せず、 abstract 属性を指定し、次のコードスニペットに示すように、 true の値で抽象属性を指定する必要があります-

<?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-3.0.xsd">

   <bean id = "beanTeamplate" abstract = "true">
      <property name = "message1" value = "Hello World!"/>
      <property name = "message2" value = "Hello Second World!"/>
      <property name = "message3" value = "Namaste India!"/>
   </bean>

   <bean id = "helloIndia" class = "com.finddevguides.HelloIndia" parent = "beanTeamplate">
      <property name = "message1" value = "Hello India!"/>
      <property name = "message3" value = "Namaste India!"/>
   </bean>

</beans>

親Beanは不完全であるため、単独ではインスタンス化できません。また、_abstract_として明示的にマークされています。 定義がこのように抽象的である場合、子定義の親定義として機能する純粋なテンプレートBean定義としてのみ使用できます。

春-依存性注入

すべてのJavaベースのアプリケーションには、連携して動作し、エンドユーザーが動作しているアプリケーションと見なすものを提示するオブジェクトがいくつかあります。 複雑なJavaアプリケーションを記述する場合、アプリケーションクラスは他のJavaクラスから可能な限り独立している必要があります。これにより、これらのクラスを再利用し、ユニットテスト中に他のクラスとは独立してテストできるようになります。 依存性注入(またはワイヤリングと呼ばれることもあります)は、これらのクラスを接着し、同時にそれらを独立した状態に保つのに役立ちます。

テキストエディタコンポーネントを備えたアプリケーションがあり、スペルチェックを提供したいと考えています。 標準コードは次のようになります-

public class TextEditor {
   private SpellChecker spellChecker;

   public TextEditor() {
      spellChecker = new SpellChecker();
   }
}

ここで行ったことは、TextEditorとSpellCheckerの間に依存関係を作成することです。 制御の反転シナリオでは、代わりにこのようなことをします-

public class TextEditor {
   private SpellChecker spellChecker;

   public TextEditor(SpellChecker spellChecker) {
      this.spellChecker = spellChecker;
   }
}

ここでは、TextEditorはSpellCheckerの実装について心配するべきではありません。 SpellCheckerは独立して実装され、TextEditorのインスタンス化時にTextEditorに提供されます。 この手順全体は、Spring Frameworkによって制御されます。

ここでは、TextEditorから完全なコントロールを削除し、別の場所に保持しています(つまり、 XML構成ファイル)と依存関係(つまり クラスSpellChecker)は、 Class Constructor を介してクラスTextEditorに注入されています。 したがって、依存関係を外部システムに効果的に委任しているため、制御の流れは依存性注入(DI)によって「反転」されています。

依存関係を注入する2番目の方法は、SpellCheckerインスタンスを作成するTextEditorクラスの* Setterメソッド*を使用することです。 このインスタンスは、セッターメソッドを呼び出してTextEditorのプロパティを初期化するために使用されます。

したがって、DIは2つの主要なバリアントに存在し、次の2つのサブチャプターは例でそれらの両方をカバーします-

Sr.No. Dependency Injection Type & Description
1

Constructor-based dependency injection

コンストラクターベースのDIは、コンテナーが、それぞれが他のクラスへの依存関係を表すいくつかの引数を使用してクラスコンストラクターを呼び出すときに実現されます。

2

Setter-based dependency injection

セッターベースのDIは、引数のないコンストラクターまたは引数のない静的ファクトリーメソッドを呼び出してBeanをインスタンス化した後に、コンテナーがBeanでセッターメソッドを呼び出すことによって実現されます。

コンストラクターベースのDIとセッターベースのDIの両方を混在させることができますが、必須の依存関係にはコンストラクター引数を使用し、オプションの依存関係にはセッターを使用することをお勧めします。

コードはDIの原則により簡潔になり、オブジェクトに依存関係が提供されると、分離がより効果的になります。 オブジェクトは依存関係を検索せず、依存関係の場所やクラスを認識しません。むしろ、Spring Frameworkがすべてを処理します。

春-インナーBeanの注入

ご存じのとおり、Java内部クラスは他のクラスのスコープ内で定義されます。同様に、*インナーBean *は別のBeanのスコープ内で定義されるBeanです。 したがって、<property/>または<constructor-arg/>要素内の<bean/>要素はインナーBeanと呼ばれ、以下に示されています。

<?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-3.0.xsd">

   <bean id = "outerBean" class = "...">
      <property name = "target">
         <bean id = "innerBean" class = "..."/>
      </property>
   </bean>

</beans>

作業中のEclipse IDEを用意し、次の手順に従ってSpringアプリケーションを作成します。

Steps Description
1 Create a project with a name SpringExample and create a package com.finddevguides under the *src *folder in the created project.
2 Add required Spring libraries using Add External JARs option as explained in the Spring Hello World Example chapter.
3 Create Java classes TextEditor, SpellChecker and MainApp under the com.finddevguides package.
4 Create Beans configuration file Beans.xml under the* src* folder.
5 The final step is to create the content of all the Java files and Bean Configuration file and run the application as explained below.

以下は TextEditor.java ファイルの内容です-

package com.finddevguides;

public class TextEditor {
   private SpellChecker spellChecker;

  //a setter method to inject the dependency.
   public void setSpellChecker(SpellChecker spellChecker) {
      System.out.println("Inside setSpellChecker." );
      this.spellChecker = spellChecker;
   }

  //a getter method to return spellChecker
   public SpellChecker getSpellChecker() {
      return spellChecker;
   }
   public void spellCheck() {
      spellChecker.checkSpelling();
   }
}

以下は、別の依存クラスファイル SpellChecker.java の内容です-

package com.finddevguides;

public class SpellChecker {
   public SpellChecker(){
      System.out.println("Inside SpellChecker constructor." );
   }
   public void checkSpelling(){
      System.out.println("Inside checkSpelling." );
   }
}

以下は MainApp.java ファイルの内容です-

package com.finddevguides;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MainApp {
   public static void main(String[] args) {
      ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml");
      TextEditor te = (TextEditor) context.getBean("textEditor");
      te.spellCheck();
   }
}

以下は、設定ファイル Beans.xml です。このファイルには、セッターベースのインジェクションの設定がありますが、*内部Bean *が使用されています-

<?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-3.0.xsd">

   <!-- Definition for textEditor bean using inner bean -->
   <bean id = "textEditor" class = "com.finddevguides.TextEditor">
      <property name = "spellChecker">
         <bean id = "spellChecker" class = "com.finddevguides.SpellChecker"/>
      </property>
   </bean>

</beans>

ソースおよびBean構成ファイルの作成が完了したら、アプリケーションを実行しましょう。 すべてがあなたのアプリケーションでうまくいけば、それは次のメッセージを印刷します-

Inside SpellChecker constructor.
Inside setSpellChecker.
Inside checkSpelling.

春-インジェクションコレクション

Bean構成ファイルの<property>タグの ref 属性を使用して、 value 属性とオブジェクト参照を使用してプリミティブデータ型を構成する方法を見てきました。 どちらの場合も、特異値をBeanに渡すことを扱います。

List、Set、Map、PropertiesなどのJava Collectionタイプのような複数の値を渡したい場合はどうでしょう。 状況を処理するために、Springは次の4種類のコレクション構成要素を提供しています-

Sr.No Element & Description
1

<list>

これは、配線、つまり値のリストの挿入、重複の許可に役立ちます。

2

<set>

これは、値のセットを重複させることなく配線するのに役立ちます。

3

<map>

これは、名前と値が任意のタイプである名前と値のペアのコレクションを注入するために使用できます。

4

<props>

これは、名前と値が両方とも文字列である名前と値のペアのコレクションを注入するために使用できます。

<list>または<set>を使用して、java.util.Collectionまたは array の実装を配線できます。

(a)コレクションの直接値を渡すこと、および(b)Beanの参照をコレクション要素の1つとして渡すことの2つの状況に遭遇します。

動作するEclipse IDEを用意し、次の手順を実行してSpringアプリケーションを作成します。

Steps Description
1 Create a project with a name SpringExample and create a package com.finddevguides under the *src *folder in the created project.
2 Add required Spring libraries using Add External JARs option as explained in the Spring Hello World Example chapter.
3 Create Java classes JavaCollection, and MainApp under the com.finddevguides package.
4 Create Beans configuration file Beans.xml under the* src* folder.
5 The final step is to create the content of all the Java files and Bean Configuration file and run the application as explained below.

これは JavaCollection.java ファイルの内容です-

package com.finddevguides;
import java.util.*;

public class JavaCollection {
   List addressList;
   Set  addressSet;
   Map  addressMap;
   Properties addressProp;

  //a setter method to set List
   public void setAddressList(List addressList) {
      this.addressList = addressList;
   }

  //prints and returns all the elements of the list.
   public List getAddressList() {
      System.out.println("List Elements :"  + addressList);
      return addressList;
   }

  //a setter method to set Set
   public void setAddressSet(Set addressSet) {
      this.addressSet = addressSet;
   }

  //prints and returns all the elements of the Set.
   public Set getAddressSet() {
      System.out.println("Set Elements :"  + addressSet);
      return addressSet;
   }

  //a setter method to set Map
   public void setAddressMap(Map addressMap) {
      this.addressMap = addressMap;
   }

  //prints and returns all the elements of the Map.
   public Map getAddressMap() {
      System.out.println("Map Elements :"  + addressMap);
      return addressMap;
   }

  //a setter method to set Property
   public void setAddressProp(Properties addressProp) {
      this.addressProp = addressProp;
   }

  //prints and returns all the elements of the Property.
   public Properties getAddressProp() {
      System.out.println("Property Elements :"  + addressProp);
      return addressProp;
   }
}

以下は MainApp.java ファイルの内容です-

package com.finddevguides;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MainApp {
   public static void main(String[] args) {
      ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml");
      JavaCollection jc=(JavaCollection)context.getBean("javaCollection");

      jc.getAddressList();
      jc.getAddressSet();
      jc.getAddressMap();
      jc.getAddressProp();
   }
}

以下は、すべてのタイプのコレクションの構成を含む構成ファイル Beans.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-3.0.xsd">

   <!-- Definition for javaCollection -->
   <bean id = "javaCollection" class = "com.finddevguides.JavaCollection">

      <!-- results in a setAddressList(java.util.List) call -->
      <property name = "addressList">
         <list>
            <value>INDIA</value>
            <value>Pakistan</value>
            <value>USA</value>
            <value>USA</value>
         </list>
      </property>

      <!-- results in a setAddressSet(java.util.Set) call -->
      <property name = "addressSet">
         <set>
            <value>INDIA</value>
            <value>Pakistan</value>
            <value>USA</value>
            <value>USA</value>
         </set>
      </property>

      <!-- results in a setAddressMap(java.util.Map) call -->
      <property name = "addressMap">
         <map>
            <entry key = "1" value = "INDIA"/>
            <entry key = "2" value = "Pakistan"/>
            <entry key = "3" value = "USA"/>
            <entry key = "4" value = "USA"/>
         </map>
      </property>

      <!-- results in a setAddressProp(java.util.Properties) call -->
      <property name = "addressProp">
         <props>
            <prop key = "one">INDIA</prop>
            <prop key = "one">INDIA</prop>
            <prop key = "two">Pakistan</prop>
            <prop key = "three">USA</prop>
            <prop key = "four">USA</prop>
         </props>
      </property>
   </bean>

</beans>

ソースおよびBean構成ファイルの作成が完了したら、アプリケーションを実行しましょう。 すべてがあなたのアプリケーションでうまくいけば、それは次のメッセージを印刷します-

List Elements :[INDIA, Pakistan, USA, USA]
Set Elements :[INDIA, Pakistan, USA]
ap Elements :{1 = INDIA, 2 = Pakistan, 3 = USA, 4 = USA}
Property Elements :{two = Pakistan, one = INDIA, three = USA, four = USA}

Bean参照の注入

次のBean定義は、コレクションの要素の1つとしてBean参照を注入する方法を理解するのに役立ちます。 次のコードスニペットに示すように、参照と値をすべて一緒に混在させることもできます-

<?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-3.0.xsd">

   <!-- Bean Definition to handle references and values -->
   <bean id = "..." class = "...">

      <!-- Passing bean reference  for java.util.List -->
      <property name = "addressList">
         <list>
            <ref bean = "address1"/>
            <ref bean = "address2"/>
            <value>Pakistan</value>
         </list>
      </property>

      <!-- Passing bean reference  for java.util.Set -->
      <property name = "addressSet">
         <set>
            <ref bean = "address1"/>
            <ref bean = "address2"/>
            <value>Pakistan</value>
         </set>
      </property>

      <!-- Passing bean reference  for java.util.Map -->
      <property name = "addressMap">
         <map>
            <entry key = "one" value = "INDIA"/>
            <entry key = "two" value-ref = "address1"/>
            <entry key = "three" value-ref = "address2"/>
         </map>
      </property>
   </bean>

</beans>

上記のBean定義を使用するには、参照も処理できるようにセッターメソッドを定義する必要があります。

nullおよび空の文字列値を注入する

あなたが値として空の文字列を渡す必要がある場合は、次のように渡すことができます-

<bean id = "..." class = "exampleBean">
   <property name = "email" value = ""/>
</bean>

上記の例はJavaコードと同等です:exampleBean.setEmail( "")

あなたがNULL値を渡す必要がある場合は、次のように渡すことができます-

<bean id = "..." class = "exampleBean">
   <property name = "email"><null/></property>
</bean>

上記の例は、Javaコードと同等です:exampleBean.setEmail(null)

春-豆の自動配線

XML構成ファイルで<bean>要素を使用してBeanを宣言し、<constructor-arg>および<property>要素を使用して<bean>を挿入する方法を学習しました。

Springコンテナは、<constructor-arg>要素と<property>要素を使用せずに、コラボレーションするBean間の関係を「自動配線」できます。これにより、大きなSpringベースのアプリケーション用に記述するXML構成の量を削減できます。

自動配線モード

次に、自動配線モードを示します。これは、依存関係の注入に自動配線を使用するようSpringコンテナに指示するために使用できます。 <bean/>要素のautowire属性を使用して、Bean定義の autowire モードを指定します。

Sr.No Mode & Description
1

no

これはデフォルト設定であり、自動配線は行われず、配線には明示的なBean参照を使用する必要があります。 この配線に対して特別なことをする必要はありません。 これは、依存性注入の章ですでに見たものです。

2

byName

プロパティ名による自動配線。 Springコンテナは、XML設定ファイルで_autowire_属性が_byName_に設定されているBeanのプロパティを調べます。 次に、構成ファイル内の同じ名前で定義されたBeanとそのプロパティを一致させ、配線しようとします。

3

byType

プロパティデータ型による自動配線。 Springコンテナは、XML設定ファイルで_autowire_属性が_byType_に設定されているBeanのプロパティを調べます。 次に、 type が構成ファイル内のBean名の1つと正確に一致する場合、プロパティの一致と配線を試みます。 そのようなBeanが複数存在する場合、致命的な例外がスローされます。

4

constructor

byTypeに似ていますが、タイプはコンストラクター引数に適用されます。 コンテナ内にコンストラクタ引数タイプのBeanが1つしかない場合、致命的なエラーが発生します。

5

autodetect

Springはまず_constructor_による自動配線を使用して配線しようとします。動作しない場合、Springは_byType_による自動配線を試行します。

*byType* または *constructor* 自動配線モードを使用して、配列や他の型付きコレクションを配線できます。

自動配線の制限

自動配線は、プロジェクト全体で一貫して使用される場合に最適に機能します。 自動配線が一般的に使用されていない場合、開発者がそれを使用して1つまたは2つのBean定義のみを配線するのは混乱を招く可能性があります。 ただし、自動配線を使用すると、プロパティまたはコンストラクター引数を指定する必要性を大幅に減らすことができますが、使用する前に自動配線の制限と欠点を考慮する必要があります。

Sr.No. Limitations & Description
1

Overriding possibility

常に自動配線をオーバーライドする<constructor-arg>および<property>設定を使用して依存関係を指定できます。

2

Primitive data types

プリミティブ、文字列、クラスなどのいわゆる単純なプロパティを自動配線することはできません。

3

Confusing nature

自動配線は明示的な配線ほど正確ではないため、可能であれば明示的な配線を使用することをお勧めします。

Spring-注釈ベースの構成

Spring 2.5以降では、*注釈*を使用して依存性注入を構成できるようになりました。 したがって、XMLを使用してBeanのワイヤリングを記述する代わりに、関連するクラス、メソッド、またはフィールド宣言の注釈を使用して、Bean構成をコンポーネントクラス自体に移動できます。

注釈注入は、XML注入の前に実行されます。 したがって、後者の構成は、両方のアプローチで配線されたプロパティの前者をオーバーライドします。

デフォルトでは、アノテーションワイヤリングはSpringコンテナでオンになっていません。 そのため、注釈ベースの配線を使用する前に、Spring構成ファイルでそれを有効にする必要があります。 したがって、Springアプリケーションで注釈を使用する場合は、次の構成ファイルを検討してください。

<?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:context = "http://www.springframework.org/schema/context"
   xsi:schemaLocation = "http://www.springframework.org/schema/beans
   http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
   http://www.springframework.org/schema/context
   http://www.springframework.org/schema/context/spring-context-3.0.xsd">

   <context:annotation-config/>
   <!-- bean definitions go here -->

</beans>

<context:annotation-config/>が構成されたら、Springが自動的に値をプロパティ、メソッド、およびコンストラクターにワイヤリングすることを示すためにコードに注釈を付け始めることができます。 それらがどのように機能するかを理解するためにいくつかの重要な注釈を見てみましょう-

Sr.No. Annotation & Description
1

@Required

@Required注釈は、Beanプロパティのセッターメソッドに適用されます。

2

@Autowired

@Autowiredアノテーションは、Beanプロパティセッターメソッド、非セッターメソッド、コンストラクター、およびプロパティに適用できます。

3

@Qualifier

@Autowiredとともに@Qualifierアノテーションを使用して、どの正確なBeanを配線するかを指定することで混乱を取り除くことができます。

4

JSR-250 Annotations

Springは、@ Resource、@ PostConstruct、@ PreDestroyアノテーションを含むJSR-250ベースのアノテーションをサポートしています。

Spring-Javaベースの構成

これまで、XML構成ファイルを使用してSpring Beanを構成する方法を見てきました。 XML構成に慣れている場合は、使用可能な構成のいずれかを使用して同じ結果を達成するため、Javaベースの構成を続行する方法を学ぶ必要はありません。

Javaベースの構成オプションにより、この章で説明するいくつかのJavaベースのアノテーションを使用して、XMLなしでほとんどのSpring構成を記述できます。

@Configurationおよび@Beanアノテーション

クラスに @ Configuration の注釈を付けると、Spring IoCコンテナーがそのクラスをBean定義のソースとして使用できることを示します。 @ Bean アノテーションは、@ Beanアノテーションが付けられたメソッドが、SpringアプリケーションコンテキストでBeanとして登録されるべきオブジェクトを返すことをSpringに伝えます。 最も簡単な@Configurationクラスは次のようになります-

package com.finddevguides;
import org.springframework.context.annotation.*;

@Configuration
public class HelloWorldConfig {
   @Bean
   public HelloWorld helloWorld(){
      return new HelloWorld();
   }
}

上記のコードは、次のXML構成と同等になります-

<beans>
   <bean id = "helloWorld" class = "com.finddevguides.HelloWorld"/>
</beans>

ここでは、メソッド名に@Beanアノテーションが付けられ、Bean IDとして機能し、実際のBeanを作成して返します。 構成クラスには、複数の@Beanの宣言を含めることができます。 構成クラスが定義されると、次のように_AnnotationConfigApplicationContext_を使用してSpringコンテナにロードして提供できます-

public static void main(String[] args) {
   ApplicationContext ctx = new AnnotationConfigApplicationContext(HelloWorldConfig.class);

   HelloWorld helloWorld = ctx.getBean(HelloWorld.class);
   helloWorld.setMessage("Hello World!");
   helloWorld.getMessage();
}

次のように、さまざまな構成クラスをロードできます-

public static void main(String[] args) {
   AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();

   ctx.register(AppConfig.class, OtherConfig.class);
   ctx.register(AdditionalConfig.class);
   ctx.refresh();

   MyService myService = ctx.getBean(MyService.class);
   myService.doStuff();
}

動作するEclipse IDEを用意し、次の手順を実行してSpringアプリケーションを作成します。

Steps Description
1 Create a project with a name SpringExample and create a package com.finddevguides under the src folder in the created project.
2 Add required Spring libraries using Add External JARs option as explained in the Spring Hello World Example chapter.
3 Because you are using Java-based annotations, so you also need to add CGLIB.jar from your Java installation directory and ASM.jar library which can be downloaded from asm.ow2.org.
4 Create Java classes HelloWorldConfig, HelloWorld and MainApp under the com.finddevguides package.
5 The final step is to create the content of all the Java files and Bean Configuration file and run the application as explained below.
*HelloWorldConfig.java* ファイルの内容は次のとおりです。
package com.finddevguides;
import org.springframework.context.annotation.*;

@Configuration
public class HelloWorldConfig {
   @Bean
   public HelloWorld helloWorld(){
      return new HelloWorld();
   }
}
*HelloWorld.java* ファイルの内容は次のとおりです。
package com.finddevguides;

public class HelloWorld {
   private String message;

   public void setMessage(String message){
      this.message  = message;
   }
   public void getMessage(){
      System.out.println("Your Message : " + message);
   }
}

以下は MainApp.java ファイルの内容です

package com.finddevguides;

import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.*;

public class MainApp {
   public static void main(String[] args) {
      ApplicationContext ctx =
         new AnnotationConfigApplicationContext(HelloWorldConfig.class);

      HelloWorld helloWorld = ctx.getBean(HelloWorld.class);
      helloWorld.setMessage("Hello World!");
      helloWorld.getMessage();
   }
}

すべてのソースファイルを作成し、必要な追加ライブラリを追加したら、アプリケーションを実行しましょう。 設定ファイルは必要ないことに注意してください。 すべてがあなたのアプリケーションでうまくいけば、それは次のメッセージを印刷します-

Your Message : Hello World!

Bean依存関係の注入

@Beansが互いに依存関係を持っている場合、依存関係は、次のように別のBeanメソッドを呼び出すことと同じくらい簡単であることを表現します-

package com.finddevguides;
import org.springframework.context.annotation.*;

@Configuration
public class AppConfig {
   @Bean
   public Foo foo() {
      return new Foo(bar());
   }
   @Bean
   public Bar bar() {
      return new Bar();
   }
}

ここで、foo Beanは、コンストラクター注入を介してbarへの参照を受け取ります。 次に、別の実用的な例を見てみましょう。

動作するEclipse IDEを用意し、次の手順を実行してSpringアプリケーションを作成します。

Steps Description
1 Create a project with a name SpringExample and create a package com.finddevguides under the src folder in the created project.
2 Add required Spring libraries using Add External JARs option as explained in the Spring Hello World Example chapter.
3 Because you are using Java-based annotations, so you also need to add CGLIB.jar from your Java installation directory and ASM.jar library which can be downloaded from asm.ow2.org.
4 Create Java classes TextEditorConfig, TextEditor, SpellChecker and MainApp under the com.finddevguides package.
5 The final step is to create the content of all the Java files and Bean Configuration file and run the application as explained below.
*TextEditorConfig.java* ファイルの内容は次のとおりです。
package com.finddevguides;
import org.springframework.context.annotation.*;

@Configuration
public class TextEditorConfig {
   @Bean
   public TextEditor textEditor(){
      return new TextEditor( spellChecker() );
   }

   @Bean
   public SpellChecker spellChecker(){
      return new SpellChecker( );
   }
}
*TextEditor.java* ファイルの内容は次のとおりです。
package com.finddevguides;

public class TextEditor {
   private SpellChecker spellChecker;

   public TextEditor(SpellChecker spellChecker){
      System.out.println("Inside TextEditor constructor." );
      this.spellChecker = spellChecker;
   }
   public void spellCheck(){
      spellChecker.checkSpelling();
   }
}

以下は、別の依存クラスファイル SpellChecker.java の内容です。

package com.finddevguides;

public class SpellChecker {
   public SpellChecker(){
      System.out.println("Inside SpellChecker constructor." );
   }
   public void checkSpelling(){
      System.out.println("Inside checkSpelling." );
   }
}

以下は MainApp.java ファイルの内容です

package com.finddevguides;

import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.*;

public class MainApp {
   public static void main(String[] args) {
      ApplicationContext ctx =
         new AnnotationConfigApplicationContext(TextEditorConfig.class);

      TextEditor te = ctx.getBean(TextEditor.class);
      te.spellCheck();
   }
}

すべてのソースファイルを作成し、必要な追加ライブラリを追加したら、アプリケーションを実行しましょう。 設定ファイルは必要ないことに注意してください。 すべてがあなたのアプリケーションでうまくいけば、それは次のメッセージを印刷します-

Inside SpellChecker constructor.
Inside TextEditor constructor.
Inside checkSpelling.

@Importアノテーション

*@ Import* 注釈を使用すると、別の構成クラスから@Bean定義をロードできます。 次のようにConfigAクラスを検討してください-
@Configuration
public class ConfigA {
   @Bean
   public A a() {
      return new A();
   }
}

次のように、別のBean宣言で上記のBean宣言をインポートできます-

@Configuration
@Import(ConfigA.class)
public class ConfigB {
   @Bean
   public B b() {
      return new B();
   }
}

今、コンテキストをインスタンス化するときにConfigA.classとConfigB.classの両方を指定する必要はなく、ConfigBのみを次のように指定する必要があります-

public static void main(String[] args) {
   ApplicationContext ctx = new AnnotationConfigApplicationContext(ConfigB.class);

  //now both beans A and B will be available...
   A a = ctx.getBean(A.class);
   B b = ctx.getBean(B.class);
}

ライフサイクルコールバック

@Beanアノテーションは、Spring XMLのBean要素のinit-methodおよびdestroy-method属性と同様に、任意の初期化および破棄コールバックメソッドの指定をサポートします-

public class Foo {
   public void init() {
     //initialization logic
   }
   public void cleanup() {
     //destruction logic
   }
}
@Configuration
public class AppConfig {
   @Bean(initMethod = "init", destroyMethod = "cleanup" )
   public Foo foo() {
      return new Foo();
   }
}

Beanスコープの指定

デフォルトのスコープはシングルトンですが、次のように@Scopeアノテーションでこれをオーバーライドできます-

@Configuration
public class AppConfig {
   @Bean
   @Scope("prototype")
   public Foo foo() {
      return new Foo();
   }
}

春のイベント処理

すべての章で、SpringのコアはBeanの完全なライフサイクルを管理する ApplicationContext であることを確認しました。 ApplicationContextは、Beanをロードするときに特定のタイプのイベントを公開します。 たとえば、コンテキストの開始時に_ContextStartedEvent_が発行され、コンテキストの停止時に_ContextStoppedEvent_が発行されます。

_ApplicationContext_でのイベント処理は、_ApplicationEvent_クラスと_ApplicationListener_インターフェイスを介して提供されます。 したがって、豆を実装_ApplicationListener_場合、_ApplicationEvent_はApplicationContextのに公開されるたびに、そのBeanが通知されます。

春は、次の標準イベントを提供します-

Sr.No. Spring Built-in Events & Description
1

ContextRefreshedEvent

このイベントは、_ApplicationContext_が初期化または更新されると公開されます。 これは、_ConfigurableApplicationContext_インターフェースのrefresh()メソッドを使用して発生させることもできます。

2

ContextStartedEvent

このイベントは、_ConfigurableApplicationContext_インターフェースのstart()メソッドを使用して_ApplicationContext_が開始されると公開されます。 データベースをポーリングするか、このイベントを受け取った後に停止したアプリケーションを再起動できます。

3

ContextStoppedEvent

このイベントは、_ConfigurableApplicationContext_インターフェースのstop()メソッドを使用して_ApplicationContext_が停止されると公開されます。 このイベントを受け取った後、必要なハウスキープ作業を行うことができます。

4

ContextClosedEvent

このイベントは、_ConfigurableApplicationContext_インターフェースのclose()メソッドを使用して_ApplicationContext_が閉じられると公開されます。 閉じたコンテキストは、その寿命の終わりに達します。更新または再起動できません。

5

RequestHandledEvent

これは、HTTPリクエストが処理されたことをすべてのBeanに伝えるWeb固有のイベントです。

Springのイベント処理はシングルスレッドであるため、イベントが公開された場合、すべての受信者がメッセージを受信するまで、プロセスがブロックされ、フローは続行されません。 したがって、イベント処理を使用する場合は、アプリケーションの設計時に注意が必要です。

コンテキストイベントを聞く

コンテキストイベントをリッスンするには、Beanは* onApplicationEvent()*メソッドを1つだけ持つ_ApplicationListener_インターフェイスを実装する必要があります。 したがって、イベントがどのように伝播し、特定のイベントに基づいて必要なタスクを実行するようにコードを配置する方法を確認するための例を作成しましょう。

動作するEclipse IDEを用意し、次の手順を実行してSpringアプリケーションを作成します。

Step Description
1 Create a project with a name SpringExample and create a package com.finddevguides under the *src *folder in the created project.
2 Add required Spring libraries using Add External JARs option as explained in the Spring Hello World Example chapter.
3 Create Java classes HelloWorld, CStartEventHandler, CStopEventHandler and MainApp under the com.finddevguides package.
4 Create Beans configuration file Beans.xml under the* src* folder.
5 The final step is to create the content of all the Java files and Bean Configuration file and run the application as explained below.
*HelloWorld.java* ファイルの内容は次のとおりです。
package com.finddevguides;

public class HelloWorld {
   private String message;

   public void setMessage(String message){
      this.message  = message;
   }
   public void getMessage(){
      System.out.println("Your Message : " + message);
   }
}

以下は CStartEventHandler.java ファイルの内容です。

package com.finddevguides;

import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextStartedEvent;

public class CStartEventHandler
   implements ApplicationListener<ContextStartedEvent>{

   public void onApplicationEvent(ContextStartedEvent event) {
      System.out.println("ContextStartedEvent Received");
   }
}

以下は、 CStopEventHandler.java ファイルの内容です。

package com.finddevguides;

import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextStoppedEvent;

public class CStopEventHandler
   implements ApplicationListener<ContextStoppedEvent>{

   public void onApplicationEvent(ContextStoppedEvent event) {
      System.out.println("ContextStoppedEvent Received");
   }
}

以下は MainApp.java ファイルの内容です

package com.finddevguides;

import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MainApp {
   public static void main(String[] args) {
      ConfigurableApplicationContext context =
         new ClassPathXmlApplicationContext("Beans.xml");

     //Let us raise a start event.
      context.start();

      HelloWorld obj = (HelloWorld) context.getBean("helloWorld");
      obj.getMessage();

     //Let us raise a stop event.
      context.stop();
   }
}

以下は設定ファイル Beans.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-3.0.xsd">

   <bean id = "helloWorld" class = "com.finddevguides.HelloWorld">
      <property name = "message" value = "Hello World!"/>
   </bean>

   <bean id = "cStartEventHandler" class = "com.finddevguides.CStartEventHandler"/>
   <bean id = "cStopEventHandler" class = "com.finddevguides.CStopEventHandler"/>

</beans>

ソースおよびBean構成ファイルの作成が完了したら、アプリケーションを実行しましょう。 すべてがあなたのアプリケーションでうまくいけば、それは次のメッセージを印刷します-

ContextStartedEvent Received
Your Message : Hello World!
ContextStoppedEvent Received

必要に応じて、独自のカスタムイベントを公開し、後で同じイベントをキャプチャして、それらのカスタムイベントに対してアクションを実行できます。 独自のカスタムイベントの作成に興味がある場合は、link:/spring/custom_events_in_spring [Springのカスタムイベント]を確認してください。

春のカスタムイベント

独自のカスタムイベントを作成して公開するには、いくつかの手順を実行する必要があります。 この章の指示に従って、カスタムSpringイベントを作成、公開、および処理します。

Steps Description
1 Create a project with a name SpringExample and create a package com.finddevguides under the *src *folder in the created project. All the classes will be created under this package.
2 Add required Spring libraries using Add External JARs option as explained in the Spring Hello World Example chapter.
3 Create an event class, CustomEvent by extending* ApplicationEvent*. This class must define a default constructor which should inherit constructor from ApplicationEvent class.
4 Once your event class is defined, you can publish it from any class, let us say EventClassPublisher which implements ApplicationEventPublisherAware. You will also need to declare this class in XML configuration file as a bean so that the container can identify the bean as an event publisher because it implements the ApplicationEventPublisherAware interface.
5 A published event can be handled in a class, let us say EventClassHandler which implements ApplicationListener interface and implements onApplicationEvent method for the custom event.
6 Create beans configuration file Beans.xml under the src folder and a MainApp class which will work as Spring application.
7 The final step is to create the content of all the Java files and Bean Configuration file and run the application as explained below.
*CustomEvent.java* ファイルの内容は次のとおりです。
package com.finddevguides;

import org.springframework.context.ApplicationEvent;

public class CustomEvent extends ApplicationEvent{
   public CustomEvent(Object source) {
      super(source);
   }
   public String toString(){
      return "My Custom Event";
   }
}

以下は CustomEventPublisher.java ファイルの内容です

package com.finddevguides;

import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationEventPublisherAware;

public class CustomEventPublisher implements ApplicationEventPublisherAware {
   private ApplicationEventPublisher publisher;

   public void setApplicationEventPublisher (ApplicationEventPublisher publisher) {
      this.publisher = publisher;
   }
   public void publish() {
      CustomEvent ce = new CustomEvent(this);
      publisher.publishEvent(ce);
   }
}

以下は、 CustomEventHandler.java ファイルの内容です。

package com.finddevguides;

import org.springframework.context.ApplicationListener;

public class CustomEventHandler implements ApplicationListener<CustomEvent> {
   public void onApplicationEvent(CustomEvent event) {
      System.out.println(event.toString());
   }
}

以下は MainApp.java ファイルの内容です

package com.finddevguides;

import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MainApp {
   public static void main(String[] args) {
      ConfigurableApplicationContext context =
         new ClassPathXmlApplicationContext("Beans.xml");

      CustomEventPublisher cvp =
         (CustomEventPublisher) context.getBean("customEventPublisher");

      cvp.publish();
      cvp.publish();
   }
}

以下は設定ファイル Beans.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-3.0.xsd">

   <bean id = "customEventHandler" class = "com.finddevguides.CustomEventHandler"/>
   <bean id = "customEventPublisher" class = "com.finddevguides.CustomEventPublisher"/>

</beans>

ソースおよびBean構成ファイルの作成が完了したら、アプリケーションを実行しましょう。 すべてがあなたのアプリケーションでうまくいけば、それは次のメッセージを印刷します-

y Custom Event
y Custom Event

Spring Frameworkを使用したAOP

Spring Frameworkの重要なコンポーネントの1つは、*アスペクト指向プログラミング(AOP)*フレームワークです。 アスペクト指向プログラミングでは、プログラムロジックをいわゆる懸念と呼ばれる個別の部分に分解する必要があります。 アプリケーションの複数のポイントにまたがる機能は「横断的関心事」と呼ばれ、これらの横断的関心事は概念的にはアプリケーションのビジネスロジックから分離されています。 ロギング、監査、宣言的トランザクション、セキュリティ、キャッシングなどの側面のさまざまな一般的な良い例があります。

OOPのモジュール性の重要な単位はクラスですが、AOPのモジュール性の単位は側面です。 依存性注入は、アプリケーションオブジェクトを相互に分離するのに役立ち、AOPは、影響を受けるオブジェクトから横断的な関心事を分離するのに役立ちます。 AOPは、Perl、.NET、Javaなどのプログラミング言語のトリガーのようなものです。

Spring AOPモジュールは、アプリケーションをインターセプトするインターセプターを提供します。 たとえば、メソッドの実行時に、メソッドの実行前または実行後に機能を追加できます。

AOPの用語

AOPでの作業を開始する前に、AOPの概念と用語を理解しましょう。 これらの用語は、Springに固有のものではなく、AOPに関連しています。

Sr.No Terms & Description
1

Aspect

これは、横断的な要件を提供する一連のAPIを備えたモジュールです。 たとえば、ロギングモジュールは、ロギングのAOPアスペクトと呼ばれます。 アプリケーションは、要件に応じて任意の数の側面を持つことができます。

2

Join point

これは、AOPアスペクトをプラグインできるアプリケーション内のポイントを表します。 また、Spring AOPフレームワークを使用してアクションが実行されるアプリケーション内の実際の場所であるとも言えます。

3

Advice

これは、メソッドの実行前または実行後に実行される実際のアクションです。 これは、Spring AOPフレームワークによるプログラム実行中に呼び出される実際のコードです。

4

Pointcut

これは、アドバイスを実行する1つ以上の結合ポイントのセットです。 AOPの例で見るように、式またはパターンを使用してポイントカットを指定できます。

5

Introduction

導入により、新しいメソッドまたは属性を既存のクラスに追加できます。

6

Target object

1つ以上の側面によってアドバイスされているオブジェクト。 このオブジェクトは、常にプロキシオブジェクトであり、推奨オブジェクトとも呼ばれます。

7

Weaving

ウィービングは、アスペクトを他のアプリケーションタイプまたはオブジェクトとリンクして、推奨オブジェクトを作成するプロセスです。 これは、コンパイル時、ロード時、または実行時に実行できます。

アドバイスの種類

春の側面は、次のように言及された5種類のアドバイスで動作することができます-

Sr.No Advice & Description
1

before

メソッドを実行する前にアドバイスを実行してください。

2

after

結果に関係なく、メソッドの実行後にアドバイスを実行します。

3

after-returning

メソッドが正常に完了した場合にのみ、メソッドの実行後にアドバイスを実行します。

4

after-throwing

メソッドが例外をスローして終了する場合にのみ、メソッド実行後にアドバイスを実行します。

5

around

アドバイスされたメソッドが呼び出される前後にアドバイスを実行します。

カスタムアスペクトの実装

Springは、カスタムアスペクトを実装するために* @ AspectJアノテーションスタイル*アプローチと*スキーマベース*アプローチをサポートしています。 これら2つのアプローチは、次のセクションで詳細に説明されています。

Sr.No Approach & Description
1

XML Schema based

アスペクトは、XMLベースの構成とともに通常のクラスを使用して実装されます。

2

@AspectJ based

@AspectJは、アスペクトをJava 5アノテーションが付けられた通常のJavaクラスとして宣言するスタイルを指します。

Spring-JDBCフレームワークの概要

プレーンな古いJDBCを使用してデータベースを操作している間、例外を処理したり、データベース接続を開いたり閉じたりするために不要なコードを書くのは面倒です。 ただし、Spring JDBC Frameworkは、接続のオープン、SQLステートメントの準備と実行、例外の処理、トランザクションの処理、および最終的な接続のクローズから始まるすべての低レベルの詳細を処理します。

そのため、接続パラメーターを定義し、実行するSQLステートメントを指定し、データベースからデータをフェッチしながら各反復で必要な作業を行うだけです。

Spring JDBCは、データベースとインターフェースするためのいくつかのアプローチとそれに対応する異なるクラスを提供します。 フレームワークの JdbcTemplate クラスを使用する従来の最も一般的なアプローチを採用します。 これは、すべてのデータベース通信と例外処理を管理する中心的なフレームワーククラスです。

JdbcTemplateクラス

JDBCテンプレートクラスは、SQLクエリを実行し、ステートメントを更新し、プロシージャコールを格納し、ResultSetの反復を実行し、返されたパラメーター値を抽出します。 また、JDBC例外をキャッチし、それらをorg.springframework.daoパッケージで定義された汎用のより有益な例外階層に変換します。

_JdbcTemplate_クラスのインスタンスは、一度設定されると_threadsafe_です。 したがって、_JdbcTemplate_の単一のインスタンスを構成し、この共有参照を複数のDAOに安全に挿入できます。

JDBCテンプレートクラスを使用する際の一般的なプラクティスは、Spring構成ファイルで_DataSource_を構成し、その共有DataSource BeanをDAOクラスに依存関係注入し、JdbcTemplateがDataSourceのセッターで作成されることです。

データソースの構成

データベース TEST にデータベーステーブル Student を作成しましょう。 MySQLデータベースを使用していると想定しています。他のデータベースを使用している場合は、それに応じてDDLおよびSQLクエリを変更できます。

CREATE TABLE Student(
   ID   INT NOT NULL AUTO_INCREMENT,
   NAME VARCHAR(20) NOT NULL,
   AGE  INT NOT NULL,
   PRIMARY KEY (ID)
);

次に、データベースアクセスを取得するように自身を構成できるように、JDBCテンプレートにDataSourceを提供する必要があります。 あなたは、次のコードスニペットに示すように、コードの一部でXMLファイルのデータソースを設定することができます-

<bean id = "dataSource"
   class = "org.springframework.jdbc.datasource.DriverManagerDataSource">
   <property name = "driverClassName" value = "com.mysql.jdbc.Driver"/>
   <property name = "url" value = "jdbc:mysql://localhost:3306/TEST"/>
   <property name = "username" value = "root"/>
   <property name = "password" value = "password"/>
</bean>

データアクセスオブジェクト(DAO)

DAOは、データベースアクセスに一般的に使用されるデータアクセスオブジェクトの略です。 DAOは、データベースにデータを読み書きする手段を提供するために存在し、アプリケーションの残りの部分がアクセスするインターフェイスを介してこの機能を公開する必要があります。

SpringのDAOサポートにより、JDBC、Hibernate、JPA、JDOなどのデータアクセステクノロジーを一貫した方法で簡単に操作できます。

SQLステートメントの実行

SQLおよびJDBCテンプレートオブジェクトを使用して、データベーステーブルでCRUD(作成、読み取り、更新、削除)操作を実行する方法を見てみましょう。

整数のクエリ

String SQL = "select count(*) from Student";
int rowCount = jdbcTemplateObject.queryForInt( SQL );

長いクエリ

String SQL = "select count(*) from Student";
long rowCount = jdbcTemplateObject.queryForLong( SQL );

バインド変数を使用した簡単なクエリ

String SQL = "select age from Student where id = ?";
int age = jdbcTemplateObject.queryForInt(SQL, new Object[]{10});

文字列のクエリ

String SQL = "select name from Student where id = ?";
String name = jdbcTemplateObject.queryForObject(SQL, new Object[]{10}, String.class);
  • オブジェクトを照会して返す *
String SQL = "select* from Student where id = ?";
Student student = jdbcTemplateObject.queryForObject(
   SQL, new Object[]{10}, new StudentMapper());

public class StudentMapper implements RowMapper<Student> {
   public Student mapRow(ResultSet rs, int rowNum) throws SQLException {
      Student student = new Student();
      student.setID(rs.getInt("id"));
      student.setName(rs.getString("name"));
      student.setAge(rs.getInt("age"));

      return student;
   }
}
  • 複数のオブジェクトを照会して返す *
String SQL = "select* from Student";
List<Student> students = jdbcTemplateObject.query(
   SQL, new StudentMapper());

public class StudentMapper implements RowMapper<Student> {
   public Student mapRow(ResultSet rs, int rowNum) throws SQLException {
      Student student = new Student();
      student.setID(rs.getInt("id"));
      student.setName(rs.getString("name"));
      student.setAge(rs.getInt("age"));

      return student;
   }
}

テーブルへの行の挿入

String SQL = "insert into Student (name, age) values (?, ?)";
jdbcTemplateObject.update( SQL, new Object[]{"Zara", 11} );

テーブルへの行の更新

String SQL = "update Student set name = ? where id = ?";
jdbcTemplateObject.update( SQL, new Object[]{"Zara", 10} );

テーブルから行を削除する

String SQL = "delete Student where id = ?";
jdbcTemplateObject.update( SQL, new Object[]{20} );

DDLステートメントの実行

_jdbcTemplate_の* execute(..)*メソッドを使用して、SQLステートメントまたはDDLステートメントを実行できます。 以下は、CREATEステートメントを使用してテーブルを作成する例です-

String SQL = "CREATE TABLE Student( " +
   "ID   INT NOT NULL AUTO_INCREMENT, " +
   "NAME VARCHAR(20) NOT NULL, " +
   "AGE  INT NOT NULL, " +
   "PRIMARY KEY (ID));"

jdbcTemplateObject.execute( SQL );

Spring JDBCフレームワークの例

上記の概念に基づいて、SpringでのJDBCフレームワークの使用法を理解するのに役立ついくつかの重要な例をチェックしましょう-

Sr.No. Example & Description
1

Spring JDBC Example

この例では、簡単なJDBCベースのSpringアプリケーションの作成方法を説明します。

2

SQL Stored Procedure in Spring

SpringでJDBCを使用しているときにSQLストアドプロシージャを呼び出す方法を学びます。

Spring-トランザクション管理

データベーストランザクションは、単一の作業単位として扱われる一連のアクションです。 これらのアクションは、完全に完了するか、まったく効果がありません。 トランザクション管理は、データの整合性と一貫性を確保するためのRDBMS指向のエンタープライズアプリケーションの重要な部分です。 トランザクションの概念は、 ACID として説明される次の4つの主要なプロパティで説明できます-

  • *アトミック性-トランザクションは単一の操作単位として扱われる必要があります。つまり、操作のシーケンス全体が成功するか失敗するかのいずれかです。
  • 一貫性-これは、データベースの参照整合性、テーブル内の一意の主キーなどの一貫性を表します。
  • 分離-同時に同じデータセットで多くのトランザクション処理が行われる場合があります。 データの破損を防ぐために、各トランザクションを他のトランザクションから分離する必要があります。
  • 耐久性-トランザクションが完了したら、このトランザクションの結果を永続的にする必要があり、システム障害のためにデータベースから消去することはできません。

実際のRDBMSデータベースシステムは、各トランザクションの4つのプロパティすべてを保証します。 SQLを使用してデータベースに発行されたトランザクションの単純化されたビューは次のとおりです-

  • _begin transaction_コマンドを使用してトランザクションを開始します。
  • SQLクエリを使用して、さまざまな削除、更新、または挿入操作を実行します。
  • すべての操作が成功した場合は、_commit_を実行します。それ以外の場合は、_rollback_すべての操作を実行します。

Springフレームワークは、さまざまな基盤となるトランザクション管理APIの上に抽象レイヤーを提供します。 Springのトランザクションサポートは、トランザクション機能をPOJOに追加することにより、EJBトランザクションの代替を提供することを目的としています。 Springは、プログラムによるトランザクション管理と宣言的なトランザクション管理の両方をサポートしています。 EJBにはアプリケーションサーバーが必要ですが、アプリケーションサーバーを必要とせずにSpringトランザクション管理を実装できます。

ローカルvs. グローバルトランザクション

ローカルトランザクションはJDBC接続のような単一のトランザクションリソースに固有ですが、グローバルトランザクションは分散システムのトランザクションのような複数のトランザクションリソースにまたがることができます。

ローカルトランザクション管理は、アプリケーションコンポーネントとリソースが単一のサイトに配置され、トランザクション管理が単一のマシン上で実行されるローカルデータマネージャのみを含む集中コンピューティング環境で役立ちます。 ローカルトランザクションの実装は簡単です。

すべてのリソースが複数のシステムに分散されている分散コンピューティング環境では、グローバルトランザクション管理が必要です。 このような場合、トランザクション管理はローカルレベルとグローバルレベルの両方で行う必要があります。 分散トランザクションまたはグローバルトランザクションは複数のシステムにわたって実行され、その実行には、グローバルトランザクション管理システムと、関連するすべてのシステムのすべてのローカルデータマネージャーとの間の調整が必要です。

プログラマティックと 宣言的

Springは2種類のトランザクション管理をサポートしています-

  • link:/spring/programmatic_management [プログラムによるトランザクション管理]-これは、プログラミングを使用してトランザクションを管理する必要があることを意味します。 これにより柔軟性が非常に高くなりますが、維持するのは困難です。 *link:/spring/declarative_management [宣言型トランザクション管理]-これは、トランザクション管理をビジネスコードから分離することを意味します。 トランザクションを管理するには、注釈またはXMLベースの構成のみを使用します。

宣言的なトランザクション管理は、プログラムによるトランザクション管理よりも望ましいですが、プログラムによるトランザクション管理よりも柔軟性が低いため、コードを使用してトランザクションを制御できます。 しかし、横断的な関心事の一種として、宣言的なトランザクション管理をAOPアプローチでモジュール化できます。 Springは、Spring AOPフレームワークによる宣言的なトランザクション管理をサポートしています。

Spring Transaction Abstractions

春のトランザクションの抽象化への鍵は、次のような_org.springframework.transaction.PlatformTransactionManager_インターフェイスによって定義されています-

public interface PlatformTransactionManager {
   TransactionStatus getTransaction(TransactionDefinition definition);
   throws TransactionException;

   void commit(TransactionStatus status) throws TransactionException;
   void rollback(TransactionStatus status) throws TransactionException;
}
Sr.No Method & Description
1
  • TransactionStatus getTransaction(TransactionDefinition definition)*

このメソッドは、指定された伝播動作に従って、現在アクティブなトランザクションを返すか、新しいトランザクションを作成します。

2

void commit(TransactionStatus status)

このメソッドは、ステータスに関して、指定されたトランザクションをコミットします。

3

void rollback(TransactionStatus status)

このメソッドは、指定されたトランザクションのロールバックを実行します。

_TransactionDefinition_は、Springのトランザクションサポートのコアインターフェースであり、次のように定義されています-

public interface TransactionDefinition {
   int getPropagationBehavior();
   int getIsolationLevel();
   String getName();
   int getTimeout();
   boolean isReadOnly();
}
Sr.No Method & Description
1

int getPropagationBehavior()

このメソッドは、伝播動作を返します。 Springは、EJB CMTでよく知られているすべてのトランザクション伝播オプションを提供します。

2

int getIsolationLevel()

このメソッドは、このトランザクションが他のトランザクションの作業から分離されている度合いを返します。

3

String getName()

このメソッドは、このトランザクションの名前を返します。

4

int getTimeout()

このメソッドは、トランザクションを完了する必要がある時間を秒単位で返します。

5

boolean isReadOnly()

このメソッドは、トランザクションが読み取り専用かどうかを返します。

分離レベルの可能な値は次のとおりです-

Sr.No Isolation & Description
1

TransactionDefinition.ISOLATION_DEFAULT

これはデフォルトの分離レベルです。

2

TransactionDefinition.ISOLATION_READ_COMMITTED

ダーティリードが防止されることを示します。繰り返し不可の読み取りとファントム読み取りが発生する可能性があります。

3

TransactionDefinition.ISOLATION_READ_UNCOMMITTED

ダーティー読み取り、反復不能読み取り、および幻像読み取りが発生する可能性があることを示します。

4

TransactionDefinition.ISOLATION_REPEATABLE_READ

ダーティリードおよび繰り返し不可のリードが防止されることを示します。ファントムリードが発生する可能性があります。

5

TransactionDefinition.ISOLATION_SERIALIZABLE

ダーティー読み取り、反復不能読み取り、およびファントム読み取りが防止されることを示します。

以下は、伝播タイプの可能な値です-

Sr.No. Propagation & Description
1

TransactionDefinition.PROPAGATION_MANDATORY

現在のトランザクションをサポートします。現在のトランザクションが存在しない場合、例外をスローします。

2

TransactionDefinition.PROPAGATION_NESTED

現在のトランザクションが存在する場合、ネストされたトランザクション内で実行されます。

3

TransactionDefinition.PROPAGATION_NEVER

現在のトランザクションをサポートしていません。現在のトランザクションが存在する場合、例外をスローします。

4

TransactionDefinition.PROPAGATION_NOT_SUPPORTED

現在のトランザクションをサポートしていません。むしろ、常に非トランザクションで実行します。

5

TransactionDefinition.PROPAGATION_REQUIRED

現在のトランザクションをサポートします。存在しない場合は新しいものを作成します。

6

TransactionDefinition.PROPAGATION_REQUIRES_NEW

新しいトランザクションを作成し、現在のトランザクションが存在する場合は中断します。

7

TransactionDefinition.PROPAGATION_SUPPORTS

現在のトランザクションをサポートします。存在しない場合、非トランザクションで実行されます。

8

TransactionDefinition.TIMEOUT_DEFAULT

基になるトランザクションシステムの既定のタイムアウトを使用します。タイムアウトがサポートされていない場合は、なしを使用します。

_TransactionStatus_インターフェイスは、トランザクションコードがトランザクションの実行を制御し、トランザクションステータスを照会する簡単な方法を提供します。

public interface TransactionStatus extends SavepointManager {
   boolean isNewTransaction();
   boolean hasSavepoint();
   void setRollbackOnly();
   boolean isRollbackOnly();
   boolean isCompleted();
}
Sr.No. Method & Description
1

boolean hasSavepoint()

このメソッドは、このトランザクションが内部的にセーブポイントを保持しているかどうか、つまり、セーブポイントに基づいてネストされたトランザクションとして作成されたかどうかを返します。

2

boolean isCompleted()

このメソッドは、このトランザクションが完了したかどうか、つまり、すでにコミットまたはロールバックされているかどうかを返します。

3

boolean isNewTransaction()

このメソッドは、現在のトランザクションが新しい場合にtrueを返します。

4

boolean isRollbackOnly()

このメソッドは、トランザクションがロールバック専用としてマークされているかどうかを返します。

5

void setRollbackOnly()

このメソッドは、トランザクションをロールバック専用として設定します。

Spring-MVCフレームワーク

Spring Web MVCフレームワークは、Model-View-Controller(MVC)アーキテクチャと、柔軟で疎結合のWebアプリケーションを開発するために使用できる既製のコンポーネントを提供します。 MVCパターンにより、アプリケーションのさまざまな側面(入力ロジック、ビジネスロジック、およびUIロジック)が分離され、これらの要素間の疎結合が提供されます。

  • Model はアプリケーションデータをカプセル化し、一般にPOJOで構成されます。
  • View はモデルデータのレンダリングを担当し、一般にクライアントのブラウザーが解釈できるHTML出力を生成します。
  • Controller は、ユーザーのリクエストを処理し、適切なモデルを構築し、レンダリングのためにビューに渡します。

DispatcherServlet

Spring Webモデルビューコントローラー(MVC)フレームワークは、すべてのHTTP要求と応答を処理する_DispatcherServlet_を中心に設計されています。 Spring Web MVC _DispatcherServlet_のリクエスト処理ワークフローは、次の図に示されています-

Spring DispatcherServlet

以下は、_DispatcherServlet_への着信HTTPリクエストに対応するイベントのシーケンスです-

  • HTTPリクエストを受信した後、_DispatcherServlet_は_HandlerMapping_を参照して適切な_Controller_を呼び出します。
  • _Controller_は要求を受け取り、使用されたGETまたはPOSTメソッドに基づいて適切なサービスメソッドを呼び出します。 サービスメソッドは、定義されたビジネスロジックに基づいてモデルデータを設定し、_DispatcherServlet_にビュー名を返します。
  • _DispatcherServlet_は、_ViewResolver_からの助けを借りて、リクエスト用に定義されたビューを取得します。
  • ビューが完成すると、_DispatcherServlet_はモデルデータをビューに渡し、最終的にブラウザーでレンダリングされます。

上記のすべてのコンポーネント、つまり HandlerMapping、Controller、およびViewResolverは_WebApplicationContext_ wの一部です。これは、Webアプリケーションに必要な追加機能を備えたplainApplicationContextの拡張です。

必要な構成

*web.xml* ファイルでURLマッピングを使用して、_DispatcherServlet_で処理するリクエストをマッピングする必要があります。 以下は、 *HelloWeb* _DispatcherServlet_の宣言とマッピングを示す例です-
<web-app id = "WebApp_ID" version = "2.4"
   xmlns = "http://java.sun.com/xml/ns/j2ee"
   xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation = "http://java.sun.com/xml/ns/j2ee
   http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

   <display-name>Spring MVC Application</display-name>

   <servlet>
      <servlet-name>HelloWeb</servlet-name>
      <servlet-class>
         org.springframework.web.servlet.DispatcherServlet
      </servlet-class>
      <load-on-startup>1</load-on-startup>
   </servlet>

   <servlet-mapping>
      <servlet-name>HelloWeb</servlet-name>
      <url-pattern>*.jsp</url-pattern>
   </servlet-mapping>

</web-app>
*web.xml* ファイルは、WebアプリケーションのWebContent/WEB-INFディレクトリに保存されます。 *HelloWeb* DispatcherServletの初期化時に、フレームワークは、アプリケーションのWebContent/WEB-INFディレクトリにある *[servlet-name] -servlet.xml* という名前のファイルからアプリケーションコンテキストをロードしようとします。 この場合、ファイルは *HelloWebservlet.xml* になります。

次に、<servlet-mapping>タグは、どのDispatcherServletによってどのURLが処理されるかを示します。 ここでは、。jsp *で終わるすべてのHTTP要求が *HelloWeb DispatcherServletによって処理されます。

_ [servlet-name] -servlet.xml_としてデフォルトのファイル名を使用し、_WebContent/WEB-INF_としてデフォルトの場所を使用したくない場合、web.xmlにサーブレットリスナー_ContextLoaderListener_を追加して、このファイル名と場所をカスタマイズできます。次のファイル-

<web-app...>

   <!-------- DispatcherServlet definition goes here----->
   ....
   <context-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>/WEB-INF/HelloWeb-servlet.xml</param-value>
   </context-param>

   <listener>
      <listener-class>
         org.springframework.web.context.ContextLoaderListener
      </listener-class>
   </listener>

</web-app>

ここで、Webアプリケーションの_WebContent/WEB-INF_ディレクトリに配置された HelloWeb-servlet.xml ファイルに必要な構成を確認しましょう-

<beans xmlns = "http://www.springframework.org/schema/beans"
   xmlns:context = "http://www.springframework.org/schema/context"
   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-3.0.xsd
   http://www.springframework.org/schema/context
   http://www.springframework.org/schema/context/spring-context-3.0.xsd">

   <context:component-scan base-package = "com.finddevguides"/>

   <bean class = "org.springframework.web.servlet.view.InternalResourceViewResolver">
      <property name = "prefix" value = "/WEB-INF/jsp/"/>
      <property name = "suffix" value = ".jsp"/>
   </bean>

</beans>

以下は HelloWeb-servlet.xml ファイルに関する重要なポイントです-

  • _ [servlet-name] -servlet.xml_ファイルを使用して、定義済みのBeanを作成し、グローバルスコープで同じ名前で定義されたBeanの定義をオーバーライドします。
  • _ <context:component-scan …​> _タグは、@ Controllerや@RequestMappingなどの注釈を使用できるSpring MVC注釈スキャン機能をアクティブにするために使用されます。
  • InternalResourceViewResolver_には、ビュー名を解決するために定義されたルールがあります。 上記のルールに従って、 hello という名前の論理ビューは/WEB-INF/jsp/hello.jsp_にあるビュー実装に委任されます。

次のセクションでは、実際のコンポーネント(コントローラー、モデル、ビュー)の作成方法を示します。

コントローラーの定義

DispatcherServletは、要求をコントローラーに委任して、固有の機能を実行します。 * @ Controller 注釈は、特定のクラスがコントローラーの役割を果たすことを示します。 *@ RequestMapping 注釈は、URLをクラス全体または特定のハンドラーメソッドにマップするために使用されます。

@Controller
@RequestMapping("/hello")
public class HelloController {
   @RequestMapping(method = RequestMethod.GET)
   public String printHello(ModelMap model) {
      model.addAttribute("message", "Hello Spring MVC Framework!");
      return "hello";
   }
}
*@ Controller* アノテーションは、クラスをSpring MVCコントローラーとして定義します。 ここで、 *@ RequestMapping* の最初の使用法は、このコントローラーのすべての処理メソッドが */hello* パスに関連していることを示しています。 次の注釈** @ RequestMapping(method = RequestMethod.GET)**は、printHello()メソッドをHTTP GETリクエストを処理するコントローラのデフォルトのサービスメソッドとして宣言するために使用されます。 別のメソッドを定義して、同じURLでPOST要求を処理できます。

次のように_ @ RequestMapping_に追加の属性を追加できる別の形式で上記のコントローラーを書くことができます-

@Controller
public class HelloController {
   @RequestMapping(value = "/hello", method = RequestMethod.GET)
   public String printHello(ModelMap model) {
      model.addAttribute("message", "Hello Spring MVC Framework!");
      return "hello";
   }
}
*value* 属性は、ハンドラーメソッドがマップされるURLを示し、 *method* 属性は、HTTP GET要求を処理するサービスメソッドを定義します。 次の重要な点は、上記で定義したコントローラーについて注意する必要があります-
  • サービスメソッド内で必要なビジネスロジックを定義します。 要件ごとに、このメソッド内で別のメソッドを呼び出すことができます。
  • 定義されたビジネスロジックに基づいて、このメソッド内でモデルを作成します。 セッターの異なるモデル属性を使用できます。これらの属性は、ビューからアクセスして最終結果を表示します。 この例では、属性「message」でモデルを作成します。
  • 定義されたサービスメソッドは、モデルのレンダリングに使用される view の名前を含む文字列を返すことができます。 この例では、論理ビュー名として「hello」を返します。

JSPビューの作成

Spring MVCは、さまざまなプレゼンテーションテクノロジーの多くのタイプのビューをサポートしています。 これらは、 - などのJSP、HTML、PDF、Excelワークシート、XML、Velocityテンプレート、XSLT、JSON、AtomのフィードやRSS、JasperReportsのを、 しかし、最も一般的には、JSTLで記述されたJSPテンプレートを使用します。

/WEB-INF/hello/hello.jspに単純な hello ビューを記述しましょう-

<html>
   <head>
      <title>Hello Spring MVC</title>
   </head>

   <body>
      <h2>${message}</h2>
   </body>
</html>

ここで、 $ \ {message} はコントローラー内で設定した属性です。 ビュー内に表示される複数の属性を持つことができます。

Spring Web MVCフレームワークの例

上記の概念に基づいて、Spring Webアプリケーションの構築に役立ついくつかの重要な例をチェックしましょう-

Sr.No. Example & Description
1

Spring MVC Hello World Example

この例では、簡単なSpring Web Hello Worldアプリケーションの作成方法を説明します。

2

Spring MVC Form Handling Example

この例では、HTMLフォームを使用してSpring Webアプリケーションを作成し、データをコントローラーに送信して処理結果を表示する方法を説明します。

3

Spring Page Redirection Example

Spring MVCフレームワークでページリダイレクト機能を使用する方法を学びます。

4

Spring Static Pages Example

Spring MVC Frameworkで静的ページと動的ページにアクセスする方法を学びます。

5

Spring Exception Handling Example

Spring MVCフレームワークで例外を処理する方法を学びます。

Spring-Log4Jでのロギング

これは、Springアプリケーション内で非常に使いやすいLog4J機能です。 次の例では、Log4JとSpringの簡単な統合を説明する簡単な手順を紹介します。

すでにマシンに log4J がインストールされていると想定しています。 お持ちでない場合は、https://logging.apache.org/からダウンロードして、任意のフォルダーに圧縮ファイルを抽出することができます。 プロジェクトでは log4j-x.y.z.jar のみを使用します。

次に、作業中のEclipse IDEを用意し、次の手順を実行して、Spring Web Frameworkを使用して動的フォームベースのWebアプリケーションを開発します。

Steps Description
1 Create a project with a name SpringExample and create a package com.finddevguides under the *src *folder in the created project.
2 Add required Spring libraries using Add External JARs option as explained in the Spring Hello World Example chapter.
3 Add log4j library log4j-x.y.z.jar as well in your project using using Add External JARs.
4 Create Java classes HelloWorld and MainApp under the com.finddevguides package.
5 Create Beans configuration file Beans.xml under the* src *folder.
6 Create log4J configuration file log4j.properties under the* src* folder.
7 The final step is to create the content of all the Java files and Bean Configuration file and run the application as explained below.
*HelloWorld.java* ファイルの内容は次のとおりです。
package com.finddevguides;

public class HelloWorld {
   private String message;

   public void setMessage(String message){
      this.message  = message;
   }
   public void getMessage() {
      System.out.println("Your Message : " + message);
   }
}

2番目のファイル MainApp.java の内容は次のとおりです。

package com.finddevguides;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.apache.log4j.Logger;

public class MainApp {
   static Logger log = Logger.getLogger(MainApp.class.getName());

   public static void main(String[] args) {
      ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml");
      log.info("Going to create HelloWord Obj");
      HelloWorld obj = (HelloWorld) context.getBean("helloWorld");
      obj.getMessage();

      log.info("Exiting the program");
   }
}

情報メッセージを生成したのと同様の方法で*デバッグ*および*エラー*メッセージを生成できます。 Beans.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-3.0.xsd">

   <bean id = "helloWorld" class = "com.finddevguides.HelloWorld">
      <property name = "message" value = "Hello World!"/>
   </bean>

</beans>

以下は、Log4Jがログメッセージを生成するために必要な標準ルールを定義する log4j.properties の内容です。

# Define the root logger with appender file
log4j.rootLogger = DEBUG, FILE

# Define the file appender
log4j.appender.FILE=org.apache.log4j.FileAppender
# Set the name of the file
log4j.appender.FILE.File=C:\\log.out

# Set the immediate flush to true (default)
log4j.appender.FILE.ImmediateFlush=true

# Set the threshold to debug mode
log4j.appender.FILE.Threshold=debug

# Set the append to false, overwrite
log4j.appender.FILE.Append=false

# Define the layout for file appender
log4j.appender.FILE.layout=org.apache.log4j.PatternLayout
log4j.appender.FILE.layout.conversionPattern=%m%n

ソースおよびBean構成ファイルの作成が完了したら、アプリケーションを実行しましょう。 すべてがアプリケーションで問題ない場合、これはEclipseコンソールに次のメッセージを出力します-

Your Message : Hello World!

C:\\ドライブをチェックすると、次のようなログメッセージ log.out がさまざまなログメッセージと共に見つかるはずです-

<!-- initialization log messages -->

Going to create HelloWord Obj
Returning cached instance of singleton bean 'helloWorld'
Exiting the program

Jakarta Commons Logging(JCL)API

または、* Jakarta Commons Logging(JCL)* APIを使用して、Springアプリケーションでログを生成できます。 JCLはhttps://jakarta.apache.org/commons/logging/からダウンロードできます。 このパッケージから技術的に必要なファイルは_commons-logging-x.y.z.jar_ファイルのみです。このファイルは、上の例で_log4j-x.y.z.jar_を配置したのと同様の方法でクラスパスに配置する必要があります。

ロギング機能を使用するには、_org.apache.commons.logging.Log_オブジェクトが必要です。その後、要件に応じて次のいずれかのメソッドを呼び出すことができます-

  • fatal(オブジェクトメッセージ)
  • エラー(オブジェクトメッセージ)
  • warn(オブジェクトメッセージ)
  • info(オブジェクトメッセージ)
  • debug(オブジェクトメッセージ)
  • trace(オブジェクトメッセージ)

以下は、JCL APIを使用するMainApp.javaの置換です。

package com.finddevguides;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.apache.commons.logging. Log;
import org.apache.commons.logging. LogFactory;

public class MainApp {
   static Log log = LogFactory.getLog(MainApp.class.getName());

   public static void main(String[] args) {
      ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml");
      log.info("Going to create HelloWord Obj");
      HelloWorld obj = (HelloWorld) context.getBean("helloWorld");
      obj.getMessage();

      log.info("Exiting the program");
   }
}

プログラムをコンパイルして実行する前に、プロジェクトにcommons-logging-x.y.z.jarファイルが含まれていることを確認する必要があります。

上記の例では、残りの構成とコンテンツを変更せずに維持します。アプリケーションをコンパイルして実行すると、Log4J APIを使用した場合と同様の結果が得られます。 Spring-questions-answers