Spring-java-based-configuration

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

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();
   }
}