1. 概要

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

簡単に言えば、これは、 GenericApplicationContext クラスで定義された新しいregisterBean()メソッドのオーバーロードされたバージョンを介して実行できます。

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

2. Mavenの依存関係

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

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.7.2</version>
</parent>

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

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
</dependency>

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

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-core</artifactId>
    <version>5.3.3</version>
</dependency>

3. 機能的なBeanの登録

registerBean()APIは、2種類の機能インターフェースをパラメーターとして受け取ることができます

  • オブジェクトの作成に使用されるサプライヤー引数
  • BeanDefinitionCustomizer vararg は、BeanDefinitionをカスタマイズするための1つ以上のラムダ式を提供するために使用できます。 このインターフェースには、単一の 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を登録するために同じ方法で任意のタイプのアプリケーションコンテキストを使用できます。

インスタンスを作成するためのラムダ式を使用してbeanを登録する方法を見てみましょう。

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

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

MyService myService = (MyService) context.getBean("com.baeldung.functional.MyService"); 
 
assertTrue(myService.getRandomNumber() < 10);

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

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

次に、ラムダ式を追加してをカスタマイズすることにより、beanを登録する方法を見てみましょう。

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

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

4. 結論

このクイックチュートリアルでは、beanを登録する機能的な方法をどのように使用できるかを見てきました。

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