BeanCreationExceptionの原因を追うイラスト。依存側のinvoiceJobから、設定値0を拒否して初期化に失敗したinvoiceRulesの内部へ視線を導きます。

実装・エラー解決

Spring BootでBeanCreationExceptionが出たら|Caused byと失敗したBeanを確認

BeanCreationExceptionで最初に確認すること

自分のログでは、末尾のCaused byから例外名を控え、値が出ていれば一緒に残します。次に、その例外を包むBeanCreationExceptionのBean名を確認します。

関連記事Javaのスタックトレースの読み方|Caused byの後、どのコードを開けばいい? Caused byと自作コードの行を手掛かりに、例外の原因・渡された値・次に調べる場所を絞る手順を確認できます。 記事を読む

実行用サンプル

Bean生成時に初期化が失敗するケースと、同じBean定義のまま設定値を直すケースをJUnitで確認できます。Spring BootやWebサーバーは起動しません。

JDK 17、Maven 3.9系、Spring Framework 6.2.19。ZIPにはソース全文、pom.xml、READMEを収録しています。展開先で mvn -Dtest=BeanCreationCauseTest#findsTheFailedBeanAndInvalidValue test を実行すると、失敗時の例外チェーンだけを確認できます。

要約

まず先頭から「起動の途中でどのBeanが作れなくなったか」を控えます。次に Caused by を最後までたどり、例外名と入力値を拾います。今回開くのは invoiceRules の初期化処理と invoice.batch-size の設定です。

エラー例

invoiceJob の生成時に invoiceRules を受け取ります。Springが invoiceRules を作って initialize() を呼ぶと、値が 0 のため例外が出ます。次のログはJUnitの実行結果から4行を抜き出したものです。

ログの invoiceJob は起動が止まった入口です。1つ目の Caused by では invoiceRules、次の Caused by では設定キーと値 0 を控えます。JUnitはその失敗を期待しているので、例外が表示されてもテスト結果は BUILD SUCCESS です。

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'invoiceJob' defined in example.BeanCreationCauseTest$Config: Unsatisfied dependency expressed through method 'invoiceJob' parameter 0: Error creating bean with name 'invoiceRules' defined in example.BeanCreationCauseTest$Config: invoice.batch-size must be positive: 0
[省略]
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'invoiceRules' defined in example.BeanCreationCauseTest$Config: invoice.batch-size must be positive: 0
[省略]
Caused by: java.lang.IllegalArgumentException: invoice.batch-size must be positive: 0
[省略]
	at example.BeanCreationCauseTest$InvoiceRules.initialize(BeanCreationCauseTest.java:66)

BeanCreationCauseTest.java の全文です。

package example;

import java.util.Map;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.BeanCreationException;
import org.springframework.beans.factory.UnsatisfiedDependencyException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.MapPropertySource;

import static org.junit.jupiter.api.Assertions.*;

class BeanCreationCauseTest {
    @Test
    void findsTheFailedBeanAndInvalidValue() {
        try (var context = createContext(0)) {
            var outer = assertThrows(UnsatisfiedDependencyException.class, context::refresh);
            assertEquals("invoiceJob", outer.getBeanName());

            var failed = assertInstanceOf(BeanCreationException.class, outer.getCause());
            assertEquals("invoiceRules", failed.getBeanName());

            var root = assertInstanceOf(IllegalArgumentException.class, failed.getCause());
            assertEquals("invoice.batch-size must be positive: 0", root.getMessage());
            assertEquals("initialize", root.getStackTrace()[0].getMethodName());
            outer.printStackTrace(System.out);
        }
    }

    @Test
    void startsWhenTheSamePropertyHasAValidValue() {
        try (var context = createContext(20)) {
            context.refresh();
            assertEquals(20, context.getBean(InvoiceJob.class).rules().batchSize());
        }
    }

    private AnnotationConfigApplicationContext createContext(int batchSize) {
        var context = new AnnotationConfigApplicationContext();
        context.getEnvironment().getPropertySources().addFirst(
                new MapPropertySource("example", Map.of("invoice.batch-size", batchSize)));
        context.register(Config.class);
        return context;
    }

    @Configuration(proxyBeanMethods = false)
    static class Config {
        @Bean
        InvoiceJob invoiceJob(InvoiceRules rules) {
            return new InvoiceJob(rules);
        }

        @Bean(initMethod = "initialize")
        InvoiceRules invoiceRules(@Value("${invoice.batch-size}") int batchSize) {
            return new InvoiceRules(batchSize);
        }
    }

    record InvoiceJob(InvoiceRules rules) {}

    record InvoiceRules(int batchSize) {
        public void initialize() {
            if (batchSize < 1) {
                throw new IllegalArgumentException(
                        "invoice.batch-size must be positive: " + batchSize);
            }
        }
    }
}

修正例

このバッチは1件以上をまとめて処理する仕様なので、invoice.batch-size を 0 から 20 に直します。mvn -Dtest=BeanCreationCauseTest#startsWhenTheSamePropertyHasAValidValue test では、設定値20でコンテキストが起動し、invoiceJob から20を参照できることを確かめます。mvn test なら両ケースの2件を実行します。

実環境では、先に対象環境で有効なプロファイルを確認します。設定ファイルと環境変数など複数箇所に値がある場合は、どの設定から 0 が採用されたかまで特定します。入力検証を外して起動だけ通すと、処理件数の誤りが後の実行まで残ります。

関連記事Spring Bootの設定ファイルを外部化|locationとadditional-locationの違い 設定を直したつもりでも0が残るときは、同じJARで環境変数・JVMの-D・起動引数を重ね、どの値が採用されるかを確認します。 記事を読む

詳細

なぜそうなるのか?

SpringはBeanを生成した後、設定された初期化メソッドを呼びます。このサンプルでは @Bean(initMethod = "initialize") を使います。初期化が例外で終わると、対象のBeanと、それに依存するBeanの生成も失敗します。SpringのBean初期化コールバック

同じBean名と最深例外で、コンストラクターと初期化処理を見分ける

Error creating bean with name 'invoiceRules'と出て最深にIllegalArgumentExceptionがあっても、そこまででは、いつ失敗したかは分かりません。ここでは上のinvoice.batch-sizeの例に続き、再試行回数を使った比較をします。Spring Framework 6.2.19で、Bean名をinvoiceRules、不正なinvoice.retry-limitを0に揃え、検証する場所だけを変えます。

生成時に止まるコンストラクターで検証します。ログにBeanInstantiationExceptionが加わり、自作コードの呼び出し元に<init>が出ます。
生成の後に止まるXMLでinit-methodを指定し、initializeで同じ検証を呼びます。自作コードの呼び出し元にinitializeが出ます。
4回の実行ログを開く
[constructor retryLimit=0]
BeanCreationException: Error creating bean with name 'invoiceRules' defined in class path resource [constructor.xml]: Failed to instantiate [example.BeanCreationStageDemo$ConstructorInvoiceRules]: Constructor threw exception
BeanInstantiationException: Failed to instantiate [example.BeanCreationStageDemo$ConstructorInvoiceRules]: Constructor threw exception
IllegalArgumentException: invoice.retry-limit must be positive: 0
  at example.BeanCreationStageDemo.validateRetryLimit(BeanCreationStageDemo.java:68)
  at example.BeanCreationStageDemo$ConstructorInvoiceRules.<init>(BeanCreationStageDemo.java:56)
[init-method retryLimit=0]
BeanCreationException: Error creating bean with name 'invoiceRules' defined in class path resource [init-method.xml]: invoice.retry-limit must be positive: 0
IllegalArgumentException: invoice.retry-limit must be positive: 0
  at example.BeanCreationStageDemo.validateRetryLimit(BeanCreationStageDemo.java:68)
  at example.BeanCreationStageDemo$InitMethodInvoiceRules.initialize(BeanCreationStageDemo.java:62)
[constructor retryLimit=20]
started invoiceRules retryLimit=20
[init-method retryLimit=20]
started invoiceRules retryLimit=20

どちらも、最深のメッセージから「0を拒否した」と分かります。直すコードを探すときは、検証メソッドを呼んだ次の自作コードの1行まで見ます。<init>ならコンストラクターと渡された引数、initializeなら初期化を登録したところと初期化メソッドが使う値を調べます。クラスが違う場合は、同じ名前のinitializeがあってもログのクラス名を優先してください。

この版のXML初期化のログは、初期化専用の決まり文句を追加せず、拒否メッセージをBeanCreationExceptionへ引き継ぎました。ライブラリの版や登録方法で例外の包まれ方は変わるため、決まり文句だけで判別するより、Caused byと自作コードの呼び出し元を一緒に見る方が確実です。初期化の例外を包む箇所はSpring Framework 6.2.19のソースで確認できます。

コンストラクターと初期化処理を同じ値で比較する

JDK 17・Maven・Spring Framework 6.2.19で動く実習です。ZIPにJavaコード、XML定義、JUnit 4ケース、POM、手順を収録しました。展開した bean-stage-sample フォルダーで mvn -q compile exec:java で上の4回を再現し、mvn test で失敗時の原因と正常値の結果を確かめられます。

GitHubで実行コードとXMLを見る比較のZIPをダウンロード

両ケースともinvoice.retry-limit=20にすると起動できます。障害票には、例外名だけでなく、たとえば「invoiceRulesのinitializeがinvoice.retry-limit=0を拒否した」と書きます。修正をレビューする人が、どの定義と設定値を見直すか同じ場所から確認できます。

Beanのコンストラクターが互いを要求すると起動できない

注文Serviceが請求を依頼するために請求Serviceを必要とし、請求Serviceも金額を読むために注文Serviceを必要とする構成を試します。両方が相手をコンストラクターの引数で受け取ると、注文の作成に必要な請求を作る段階で、生成途中の注文へ戻ります。

矢印は、Beanを作るときに必要とする相手

修正前|注文と請求が互いを要求

注文
orderService
請求
invoiceService

修正後|処理を進める役が両方を使う

CheckoutWorkflow
注文
orderService
請求
invoiceService

Error creating bean with name が出たら、Caused by のBean名を上から並べます。実習の順序は orderService → invoiceService → orderService です。最深の BeanCurrentlyInCreationException を手がかりに、2つのコンストラクターを開き、互いの型を要求していることを確認します。

循環があるときの例外の抜粋
UnsatisfiedDependencyException bean=orderService
UnsatisfiedDependencyException bean=invoiceService
BeanCurrentlyInCreationException bean=orderService
Error creating bean with name 'orderService': Requested bean is currently in creation: Is there an unresolvable circular reference or an asynchronous initialization dependency?

修正版では CheckoutWorkflow が注文を取得し、取得済みの Order を請求Serviceへ渡します。請求側が必要とするのは、注文IDと金額です。下のメソッドは CheckoutWorkflow.issueInvoice() の抜粋です。

public Invoice issueInvoice(String orderId) {
    return invoices.issueFor(orders.findOrder(orderId));
}

循環した状態では、Spring FrameworkのBeanFactoryの allowCircularReferences を false と true にしても、両方で同じ原因となり、コンテナの起動が止まりました。修正版では起動後に注文 ORDER-42 を処理し、請求額 1,800円 を返します。

循環する構成と修正版を実行する

JDK 17・Maven・Spring Framework 6.2.19で動きます。ZIPにJava全文、JUnit 3件、POM、READMEを収録しています。展開した bean-constructor-cycle-sample で mvn -B -ntp test と mvn -B -q -ntp compile exec:java を実行します。サンプルのmainは期待した起動例外を捕らえ、原因を表示して修正版まで実行します。

固定GitHubでコードを見る循環依存のZIPをダウンロード

実行結果11行とJava・JUnitの全文を見る
[constructor cycle allowCircularReferences=false]
UnsatisfiedDependencyException bean=orderService
UnsatisfiedDependencyException bean=invoiceService
BeanCurrentlyInCreationException bean=orderService
Error creating bean with name 'orderService': Requested bean is currently in creation: Is there an unresolvable circular reference or an asynchronous initialization dependency?
[constructor cycle allowCircularReferences=true]
UnsatisfiedDependencyException bean=orderService
UnsatisfiedDependencyException bean=invoiceService
BeanCurrentlyInCreationException bean=orderService
Error creating bean with name 'orderService': Requested bean is currently in creation: Is there an unresolvable circular reference or an asynchronous initialization dependency?
[workflow] order=ORDER-42 totalYen=1800
package example;

import org.springframework.beans.factory.BeanCreationException;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public final class BeanConstructorCycleDemo {
    private BeanConstructorCycleDemo() {}

    public static void main(String[] args) {
        for (boolean allowCircularReferences : new boolean[] {false, true}) {
            System.out.printf("[constructor cycle allowCircularReferences=%s]%n",
                    allowCircularReferences);
            try (var context = prepareCycle(allowCircularReferences)) {
                context.refresh();
                throw new IllegalStateException("Expected the constructor cycle to stop startup");
            } catch (BeanCreationException failure) {
                for (Throwable cause = failure; cause != null; cause = cause.getCause()) {
                    if (cause instanceof BeanCreationException creation) {
                        System.out.printf("%s bean=%s%n",
                                creation.getClass().getSimpleName(), creation.getBeanName());
                    }
                }
                System.out.println(failure.getMostSpecificCause().getMessage());
            }
        }

        try (var context = prepareWorkflow()) {
            context.refresh();
            var workflow = context.getBean(CheckoutWorkflow.class);
            Invoice invoice = workflow.issueInvoice("ORDER-42");
            System.out.printf("[workflow] order=%s totalYen=%d%n",
                    invoice.orderId(), invoice.totalYen());
        }
    }

    static AnnotationConfigApplicationContext prepareCycle(boolean allowCircularReferences) {
        var context = new AnnotationConfigApplicationContext();
        context.getDefaultListableBeanFactory()
                .setAllowCircularReferences(allowCircularReferences);
        context.registerBean("orderService", CyclicOrderService.class);
        context.registerBean("invoiceService", CyclicInvoiceService.class);
        return context;
    }

    static AnnotationConfigApplicationContext prepareWorkflow() {
        var context = new AnnotationConfigApplicationContext();
        context.getDefaultListableBeanFactory().setAllowCircularReferences(false);
        context.registerBean("orderService", OrderService.class);
        context.registerBean("invoiceService", InvoiceService.class);
        context.registerBean("checkoutWorkflow", CheckoutWorkflow.class);
        return context;
    }

    // Before: each service requires the other service at construction.
    public static final class CyclicOrderService {
        private final CyclicInvoiceService invoices;

        public CyclicOrderService(CyclicInvoiceService invoices) {
            this.invoices = invoices;
        }

        public Invoice issueInvoice(String orderId) {
            return invoices.issueFor(orderId);
        }

        public Order findOrder(String orderId) {
            return new Order(orderId, 1800);
        }
    }

    public static final class CyclicInvoiceService {
        private final CyclicOrderService orders;

        public CyclicInvoiceService(CyclicOrderService orders) {
            this.orders = orders;
        }

        public Invoice issueFor(String orderId) {
            Order order = orders.findOrder(orderId);
            return new Invoice(order.id(), order.totalYen());
        }
    }

    // After: the workflow retrieves the order and passes the actual value.
    public static final class CheckoutWorkflow {
        private final OrderService orders;
        private final InvoiceService invoices;

        public CheckoutWorkflow(OrderService orders, InvoiceService invoices) {
            this.orders = orders;
            this.invoices = invoices;
        }

        public Invoice issueInvoice(String orderId) {
            return invoices.issueFor(orders.findOrder(orderId));
        }
    }

    public static final class OrderService {
        public Order findOrder(String orderId) {
            return new Order(orderId, 1800);
        }
    }

    public static final class InvoiceService {
        public Invoice issueFor(Order order) {
            return new Invoice(order.id(), order.totalYen());
        }
    }

    public record Order(String id, int totalYen) {}

    public record Invoice(String orderId, int totalYen) {}
}
package example;

import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import org.springframework.beans.factory.BeanCurrentlyInCreationException;
import org.springframework.beans.factory.UnsatisfiedDependencyException;

import static example.BeanConstructorCycleDemo.*;
import static org.junit.jupiter.api.Assertions.*;

class BeanConstructorCycleTest {
    @ParameterizedTest
    @ValueSource(booleans = {false, true})
    void constructorCycleFailsDuringRefreshForBothSettings(boolean allowCircularReferences) {
        try (var context = prepareCycle(allowCircularReferences)) {
            var top = assertThrowsExactly(UnsatisfiedDependencyException.class, context::refresh);
            assertEquals("orderService", top.getBeanName());
            var next = assertInstanceOf(UnsatisfiedDependencyException.class, top.getCause());
            assertEquals("invoiceService", next.getBeanName());
            var deepest = assertInstanceOf(BeanCurrentlyInCreationException.class,
                    top.getMostSpecificCause());
            assertEquals("orderService", deepest.getBeanName());
            assertFalse(context.isActive());
        }
    }

    @Test
    void workflowStartsAndIssuesInvoice() {
        try (var context = prepareWorkflow()) {
            context.refresh();
            var workflow = context.getBean(CheckoutWorkflow.class);
            assertEquals(new Invoice("ORDER-42", 1800), workflow.issueInvoice("ORDER-42"));
            assertTrue(context.isActive());
        }
    }
}

上の出力は、サンプルがSpring Frameworkの例外の連鎖からBean名と原因を取り出したものです。コンストラクターで互いを要求する場合の挙動はSpring Framework 6.2の依存解決の説明で確認できます。

仕組みのポイント

最深の例外が候補0件を示す場合は、その時点で登録経路を調べます。初期化メソッドの例外なら、先にその自作コードと入力を見ます。調査を引き継ぐときは「invoiceJob → invoiceRules → initialize() で設定値0を拒否」と、名前・処理・値を一緒に残します。

関連記事Spring Bootの「No qualifying bean of type」原因|DIできないときの対処法 候補0件と読めたら、要求型とSpring BootのBean登録条件を確かめます。 記事を読む 関連記事NoSuchBeanDefinitionExceptionの原因|XML・@Serviceがあるのに登録されないとき 旧XMLを併用する場合に、XMLの読み込み元と探索範囲を確認します。 記事を読む

-実装・エラー解決
-,