Spring 5の機能Bean登録

春5機能豆登録

1. 概要

Spring 5には、アプリケーションコンテキストでの機能的なBean登録のサポートが付属しています。

簡単に言えば、GenericApplicationContextクラスで定義されたthis can be done through overloaded versions of a new registerBean() methodです。

この機能の実際の例をいくつか見てみましょう。

2. Mavenの依存関係

Spring 5プロジェクトを設定する最も簡単な方法は、spring-boot-starter-parent依存関係をpom.xml:に追加してSpring Bootを使用することです。


    org.springframework.boot
    spring-boot-starter-parent
    2.0.0.RELEASE

JUnitテストでWebアプリケーションコンテキストを使用するには、この例ではspring-boot-starter-webspring-boot-starter-testも必要です。


    org.springframework.boot
    spring-boot-starter-web


    org.springframework.boot
    spring-boot-starter-test
    test

もちろん、新しい機能的な方法を使用してBeanを登録するために、Spring Bootは必要ありません。 spring-coreの依存関係を直接追加することもできます。


    org.springframework
    spring-core
    5.0.2.RELEASE

3. 機能的なBeanの登録

The registerBean() API can receive two types of functional interfaces as parameters

  • オブジェクトの作成に使用されるa Supplier argument

  • BeanDefinitionをカスタマイズするための1つ以上のラムダ式を提供するために使用できるa BeanDefinitionCustomizer vararg;このインターフェースには単一のcustomize()メソッドがあります

まず、Beanの作成に使用する非常に単純なクラス定義を作成しましょう。

public class MyService {
    public int getRandomNumber() {
        return new Random().nextInt(10);
    }
}

また、JUnitテストの実行に使用できる@SpringBootApplicationクラスを追加しましょう。

@SpringBootApplication
public class Spring5Application {
    public static void main(String[] args) {
        SpringApplication.run(Spring5Application.class, args);
    }
}

次に、@SpringBootTestアノテーションを使用してテストクラスを設定し、GenericWebApplicationContextインスタンスを作成できます。

@RunWith(SpringRunner.class)
@SpringBootTest(classes = Spring5Application.class)
public class BeanRegistrationIntegrationTest {
    @Autowired
    private GenericWebApplicationContext context;

    //...
}

この例ではGenericWebApplicationContextタイプを使用していますが、Beanを登録するために同じ方法で任意のタイプのアプリケーションコンテキストを使用できます。

we can register a bean using a lambda expression for creating the instanceがどのようになっているのか見てみましょう。

context.registerBean(MyService.class, () -> new MyService());

Beanを取得して使用できることを確認しましょう。

MyService myService = (MyService) context.getBean("com.example.functional.MyService");

assertTrue(myService.getRandomNumber() < 10);

この例では、Bean名が明示的に定義されていない場合、クラスの小文字の名前から決定されることがわかります。 上記と同じメソッドは、明示的なBean名でも使用できます。

context.registerBean("mySecondService", MyService.class, () -> new MyService());

次に、we can register a bean by adding a lambda expression to customize itがどのようになっているのか見てみましょう。

context.registerBean("myCallbackService", MyService.class,
  () -> new MyService(), bd -> bd.setAutowireCandidate(false));

この引数は、autowire-candidateフラグやprimaryフラグなどのBeanプロパティを設定するために使用できるコールバックです。

4. 結論

このクイックチュートリアルでは、Beanを登録する機能的な方法を使用する方法を説明しました。

この例のソースコードはover on GitHubにあります。