Spring BootのNo qualifying bean of typeエラーとDIできない場合の確認順を解説する記事のアイキャッチ。

実装・エラー解決

Spring Bootの「No qualifying bean of type」原因|DIできないときの対処法

AIによる要約

Spring BootのNo qualifying bean of typeは、要求した型や@Qualifierの条件を満たすBeanを見つけられないときに発生します。最初にエラーメッセージから「必要とされた型」と「要求したクラス」を特定し、その型の実装クラス、@Service・@Component・@Repository・@Bean、コンポーネントスキャン範囲を確認します。実装が複数ある場合は別のエラーであり、@Qualifierや@Primaryの検討対象です。required=falseやnullで起動だけ通すのではなく、その依存関係が必須か、どの実装を使う設計かを明確にします。

新人SE
新人SE
Serviceへコンストラクタを追加したら、アプリが起動しなくなりました。No qualifying bean of typeと出ています。
ポンコツSE
ポンコツSE
注入される側より先に、Springが探している型と、その型をBeanとして登録する定義を確認します。

ログに No qualifying bean of type が出たら、先に expected at least 1 bean と found 2 など、後半の候補数を読んでください。ここでは 候補が0件 の場合を扱います。

候補が0件になるのは、要求型のBeanが登録されていない場合と、登録はあるものの@Qualifierの指定に合うBeanがない場合です。

ログから最初に拾うのは、要求元・引数番号・要求型

UnsatisfiedDependencyException の orderService と parameter 0 で、準備できなかった引数が分かります。続く No qualifying bean of type に出る PaymentGateway が、Springの探していた型です。

Dependency annotations にQualifierの値が出ているなら、注入先とBean定義のQualifierを突き合わせる例から調べます。

この記事のポイント

  • エラー文から要求された型と要求元クラスを読む
  • 実装クラスが存在するだけではBeanにならない
  • @Service・@Component・@Repository・@Beanを確認する
  • 起動クラス配下のコンポーネントスキャン範囲を確認する
  • 候補0件と候補複数件を混同しない
  • テストのスライスが必要なBeanを読み込んでいるか確認する

実行用サンプル

必須の決済Beanが0件になる条件を比較します。外部の決済APIは呼びません。 ソース全文、JUnitの検証コード、pom.xml、READMEを収録しています。JDK 17とMaven 3.9系で mvn test を実行します。Spring Boot 3.5.16のサンプルです。

No qualifying bean of typeエラーの意味

次のようなServiceがあるとします。

OrderService.java の全文

package info.syachiku.registration.payment.sales;

import info.syachiku.registration.payment.PaymentGateway;
import org.springframework.stereotype.Service;

@Service
public class OrderService {
    private final PaymentGateway paymentGateway;

    public OrderService(PaymentGateway paymentGateway) {
        this.paymentGateway = paymentGateway;
    }

    public String authorize(String orderId) {
        return paymentGateway.authorize(orderId);
    }
}

SpringはOrderServiceを作るとき、コンストラクタ引数のPaymentGateway型を満たすBeanをコンテナから探します。候補がなければ、次のような趣旨のエラーになります。

検証時のログから、要求元の引数番号と要求型を抜粋。読みやすい位置に改行を入れています。

Unsatisfied dependency expressed through constructor parameter 0:
No qualifying bean of type 'info.syachiku.registration.payment.PaymentGateway' available:

この例で外側に出たUnsatisfiedDependencyExceptionは、OrderServiceのコンストラクタの最初の引数(parameter 0)を用意できなかったという意味です。ログのNo qualifying bean of typeは、その引数に要求されたPaymentGatewayの候補が見つからなかったことを示します。JUnitでは最深の原因がNoSuchBeanDefinitionExceptionであることも確認しています。要求元・引数番号・要求型を控えて、どの定義を調べるか絞ります。

「どの型がないか」と「誰がその型を必要としているか」をエラー文から1行ずつ拾うと、調査対象を絞れます。

原因1:実装クラスにSpringのアノテーションがない

PlainCardPaymentGateway は要求されたインターフェースを実装しています。ただし、通常のコンポーネントスキャンで登録する目印がありません。このクラスのパッケージを探索しても、テストで候補は0件です。

PlainCardPaymentGateway.java の全文

package info.syachiku.registration.payment.plain;

import info.syachiku.registration.payment.PaymentGateway;

public class PlainCardPaymentGateway implements PaymentGateway {
    @Override
    public String authorize(String orderId) {
        return "PLAIN:" + orderId;
    }
}

探索で登録する実装には、クラスの役割に合ったステレオタイプを付けます。次の CardPaymentGateway は、探索対象に含めると登録されます。

CardPaymentGateway.java の全文

package info.syachiku.registration.payment.integration;

import info.syachiku.registration.payment.PaymentGateway;
import org.springframework.stereotype.Component;

@Component
public class CardPaymentGateway implements PaymentGateway {
    @Override
    public String authorize(String orderId) {
        return "CARD:" + orderId;
    }
}

業務処理なら@Service、DBアクセスなら@Repository、Web入口なら@Controller、その他の構成要素なら@Componentが基本です。動かすためだけに全部へ@Componentを付けるのではなく、クラスの責務に合わせます。

原因2:外部ライブラリのクラスを@Bean登録していない

外部SDKを模した LibraryPaymentClient は、ソースにアノテーションを追加できない想定です。@Bean でクライアントを作り、注文Serviceが要求する PaymentGateway 型のアダプターも登録します。クライアントだけを登録しても、要求型を満たしません。

PaymentRegistration.java の抜粋。SDKクラスとアダプターの登録

    @Configuration(proxyBeanMethods = false)
    public static class ExternalLibrary {
        @Bean
        LibraryPaymentClient libraryPaymentClient() {
            return new LibraryPaymentClient();
        }

        @Bean
        PaymentGateway libraryPaymentGateway(LibraryPaymentClient client) {
            return client::requestAuthorization;
        }
    }

@Beanメソッドの戻り値型も確認します。注入先が具象型を要求しているのに、Bean定義の公開型が別のインターフェースになっていると、型の探し方によって候補にならないことがあります。基本は注入先をインターフェースへ寄せ、必要以上に具象型へ依存しません。

原因3:コンポーネントスキャン範囲から外れている

アノテーションが付いていても、Springがそのクラスを探索しなければBean登録されません。Spring Bootでは、通常は起動クラスのパッケージと、その配下が探索対象です。

PaymentRegistration.java の抜粋。探索範囲だけを変えた2構成

    @Configuration(proxyBeanMethods = false)
    @ComponentScan(basePackageClasses = OrderService.class)
    public static class SalesOnly {
    }

    @Configuration(proxyBeanMethods = false)
    @ComponentScan(basePackageClasses = {OrderService.class, CardPaymentGateway.class})
    public static class SalesAndIntegration {
    }

SalesOnly では注文側だけを探索するため0件です。SalesAndIntegration で連携側を探索対象に加えると、同じ注文Serviceが CARD:42 を返します。まず、例外が出た環境で読み込んだ設定と、実装クラスのpackage宣言を突き合わせます。

原因4:インターフェースだけ作って実装がない

設計を先に進めるためにインターフェースだけ追加し、実装クラスを作り忘れることがあります。インターフェース自体へ@Componentを付けても、通常は生成する実体がありません。

PaymentGateway.java の全文

package info.syachiku.registration.payment;

public interface PaymentGateway {
    String authorize(String orderId);
}

Spring Data JPAのRepositoryインターフェースは、規約に従えばSpringが実装を生成します。一方、自作インターフェースは自動的に実装されません。「インターフェースならDIできる」ではなく、その実体を誰が生成するかを説明できる必要があります。

候補0件と候補複数件は別の問題

No qualifying bean of typeという言葉だけを見ると、候補がない場合と、候補を1つに決められない場合を混同しがちです。ログの続きまで読みます。

状態代表的なメッセージ確認内容
候補0件could not be found実装の登録・スキャン、注入先の@Qualifier
候補複数件expected single matching bean but found 2@Qualifier、@Primary、責務分離

実装が複数ある場合は、どの実装を使うかが仕様です。片方を削除したり、適当に@Primaryを付けたりせず、呼び出し側が何を選ぶべきかを確認します。

Beanはあるのに候補0件なら、@Qualifierの値を確かめる

決済の画面でカード用と銀行振込用を使い分けるとします。PaymentGateway 型のBeanは cardGateway と bankGateway の2件です。注入先は @Qualifier でカード用を指定していますが、値の文字の順序を取り違えると、型の合うBeanが2件あっても、その注入先には候補がなくなります。

ログから注入先の指定を読むDependency annotations に出る値が card-gateawy。

Bean定義の指定を確認するcardGateway に付けた @Qualifier は card-gateway。

注入先の指定を修正して再実行するcard-gateway にそろえるとカード用のスタブが選ばれ、注文ID 42 に CARD:42 が返る。

このサンプルでは、まず注入先を読み込まない構成で登録名を確認します。失敗する構成ではBeanが正常に取得できないためです。次に、登録の構成はそのままに、注入先の値だけを変えます。cardGateway はBean名、card-gateway はこの例でBean定義に付けた選択用の値です。

3テストの出力を、登録・失敗・修正の順に並べています。

REGISTERED PaymentGateway names=[bankGateway, cardGateway]
WRONG top=UnsatisfiedDependencyException bean=checkoutService
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'example.qualifier.PaymentGateway' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Qualifier("card-gateawy")}
FIXED qualifier=card-gateway result=CARD:42

CheckoutConfigurations.javaでは、checkoutServiceを作るときの引数に付いた@Qualifierを修正しています。下の全文とBean定義を開き、両側の文字列を比べてください。

package example.qualifier;

import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

final class CheckoutConfigurations {
    private CheckoutConfigurations() {
    }

    @Configuration(proxyBeanMethods = false)
    static class WrongLabel {
        @Bean
        CheckoutService checkoutService(@Qualifier("card-gateawy") PaymentGateway gateway) {
            return new CheckoutService(gateway);
        }
    }

    @Configuration(proxyBeanMethods = false)
    static class CorrectLabel {
        @Bean
        CheckoutService checkoutService(@Qualifier("card-gateway") PaymentGateway gateway) {
            return new CheckoutService(gateway);
        }
    }
}
GatewayConfiguration.java の全文を表示する
package example.qualifier;

import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration(proxyBeanMethods = false)
class GatewayConfiguration {
    @Bean
    @Qualifier("card-gateway")
    PaymentGateway cardGateway() {
        return orderId -> "CARD:" + orderId;
    }

    @Bean
    @Qualifier("bank-gateway")
    PaymentGateway bankGateway() {
        return orderId -> "BANK:" + orderId;
    }
}
QualifierCandidateTest.java の全文を表示する
package example.qualifier;

import java.util.Set;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.beans.factory.UnsatisfiedDependencyException;
import org.springframework.boot.test.context.runner.ApplicationContextRunner;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertInstanceOf;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;

class QualifierCandidateTest {
    private static final Set<String> GATEWAY_NAMES = Set.of("cardGateway", "bankGateway");

    private final ApplicationContextRunner runner =
            new ApplicationContextRunner().withUserConfiguration(GatewayConfiguration.class);

    @Test
    void configurationRegistersTwoBeansOfTheSameType() {
        runner.run(context -> {
            assertNull(context.getStartupFailure());
            var names = context.getBeansOfType(PaymentGateway.class).keySet();
            assertEquals(GATEWAY_NAMES, names);
            System.out.println("REGISTERED PaymentGateway names=" + names.stream().sorted().toList());
        });
    }

    @Test
    void misspelledQualifierLeavesNoCandidateForTheInjectionPoint() {
        runner.withUserConfiguration(CheckoutConfigurations.WrongLabel.class).run(context -> {
            var failure = assertInstanceOf(
                    UnsatisfiedDependencyException.class, context.getStartupFailure());
            assertEquals("checkoutService", failure.getBeanName());
            Throwable cause = failure.getMostSpecificCause();
            assertEquals(NoSuchBeanDefinitionException.class, cause.getClass());
            assertTrue(cause.getMessage().contains("Dependency annotations:"));
            assertTrue(cause.getMessage().contains("card-gateawy"));

            System.out.println("WRONG top=" + failure.getClass().getSimpleName()
                    + " bean=" + failure.getBeanName());
            System.out.println("Caused by: " + cause);
        });
    }

    @Test
    void correctQualifierChoosesCardWithoutChangingRegistration() {
        runner.withUserConfiguration(CheckoutConfigurations.CorrectLabel.class).run(context -> {
            assertNull(context.getStartupFailure());
            assertEquals(GATEWAY_NAMES, context.getBeansOfType(PaymentGateway.class).keySet());
            String authorization = context.getBean(CheckoutService.class).authorize("42");
            assertEquals("CARD:42", authorization);
            System.out.println("FIXED qualifier=card-gateway result=" + authorization);
        });
    }
}

レビューでは「カード用を選ぶのはこの注入先の仕様」と説明し、注入先の指定値と定義上の指定値を並べます。ログに指定値が出ているときは、その値に合うBeanがあるかを確認してから、スキャン範囲や登録条件を調べます。Spring FrameworkのQualifierの仕様

コンストラクタインジェクションで依存関係を明確にする

フィールドへ直接@Autowiredするより、コンストラクタで必須依存を表すと、何が不足しているか読みやすくなります。コンストラクタが1つだけなら、現在の一般的なSpring構成では@Autowiredを省略できます。

OrderService.java の抜粋。必須依存を受け取るコンストラクタ

    public OrderService(PaymentGateway paymentGateway) {
        this.paymentGateway = paymentGateway;
    }

Lombokの@RequiredArgsConstructorを使う現場もありますが、生成されるコンストラクタとfinalフィールドの関係を理解してから使います。エラー調査時は、ソース上に見えないコンストラクタも意識してください。

テストだけでエラーになる場合の確認

アプリは起動するのにテストだけ失敗する場合、テストが読み込む範囲を確認します。たとえば@WebMvcTestはController周辺へ絞ったテストであり、すべてのServiceを自動で読み込むわけではありません。

OrderControllerTest.java の全文

package info.syachiku.registration.payment;

import info.syachiku.registration.payment.sales.OrderService;
import info.syachiku.registration.payment.web.OrderController;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.context.TestConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Import;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.web.servlet.MockMvc;

import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

@WebMvcTest(OrderController.class)
@ContextConfiguration(classes = OrderControllerTest.SliceApplication.class)
@Import(OrderControllerTest.TestDependencies.class)
class OrderControllerTest {
    @Autowired
    private MockMvc mvc;

    @Test
    void MVCスライスへテスト用の依存を明示するとControllerを検証できる() throws Exception {
        mvc.perform(get("/orders/42/authorization"))
                .andExpect(status().isOk())
                .andExpect(content().string("TEST:42"));
    }

    @SpringBootApplication
    static class SliceApplication {
    }

    @TestConfiguration(proxyBeanMethods = false)
    static class TestDependencies {
        @Bean
        OrderService orderService() {
            return new OrderService(orderId -> "TEST:" + orderId);
        }
    }
}

このMVCスライスでは、@TestConfiguration を読み込み、注文Serviceをテスト用の値を返す構成で用意します。HTTP 200と TEST:42 を確認します。この結果はControllerの入出力を確かめるもので、本番の決済Beanの登録は別のテストで見ます。

required=falseで起動だけ通さない

エラーを消すために@Autowired(required = false)へ変更すると、依存オブジェクトがnullのまま処理へ進み、後からNullPointerExceptionになる可能性があります。

// 原則NG: 必須なのに任意依存へ変えてしまう
@Autowired(required = false)
private PaymentGateway paymentGateway;

本当に任意機能なら、未設定時の振る舞いまで設計します。必須機能なら、正しいBean定義を追加するのが修正です。

注意

newでServiceを直接生成してDIエラーを回避すると、そのServiceが必要とする別の依存やAOP、トランザクションが適用されません。Spring管理のクラスは、既存の生成方法へ合わせてください。

現場で使える確認順

  1. 最後のCaused byまで読み、候補0件か複数件かを分ける
  2. 要求型、要求元クラス、引数番号を控える
  3. 注入先に@Qualifierがあれば、Bean定義のQualifierと一致するか確認する
  4. 該当する実装と@Service・@Component・@Repository・@Beanを確認する
  5. コンポーネントスキャンの範囲と、Profile・条件付き登録を確認する
  6. テストでだけ失敗するなら、テストが読み込むBeanの範囲を調べる

スキャン対象と登録定義が同じでも、@Profile("test-payment") が条件に合わなければ候補は0件です。配布例ではProfile未指定で起動が失敗し、spring.profiles.active=test-payment を指定すると STUB:42 を返します。

下のテストは、アノテーションなし、スキャン外、外部クライアントの明示登録、Profileを比較します。スライス1件、ステレオタイプとDBの2件を含む配布プロジェクト全体では7件です。

PaymentRegistrationTest.java の全文

package info.syachiku.registration.payment;

import info.syachiku.registration.payment.integration.CardPaymentGateway;
import info.syachiku.registration.payment.library.LibraryPaymentClient;
import info.syachiku.registration.payment.plain.PlainCardPaymentGateway;
import info.syachiku.registration.payment.sales.OrderService;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.boot.test.context.runner.ApplicationContextRunner;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

import static org.assertj.core.api.Assertions.assertThat;

class PaymentRegistrationTest {
    private final ApplicationContextRunner runner = new ApplicationContextRunner();

    @Test
    void 自作クラスをスキャンしても登録の目印がなければ候補は零件() {
        runner.withUserConfiguration(PaymentRegistration.SalesOnly.class, PlainScan.class)
                .run(context -> assertMissingGateway(context.getStartupFailure()));
    }

    @Test
    void 実装にComponentがあってもスキャン外なら候補は零件() {
        runner.withUserConfiguration(PaymentRegistration.SalesOnly.class)
                .run(context -> assertMissingGateway(context.getStartupFailure()));

        runner.withUserConfiguration(PaymentRegistration.SalesAndIntegration.class)
                .run(context -> {
                    assertThat(context.getBeansOfType(PaymentGateway.class)).hasSize(1);
                    assertThat(context.getBean(PaymentGateway.class)).isInstanceOf(CardPaymentGateway.class);
                    assertThat(context.getBean(OrderService.class).authorize("42")).isEqualTo("CARD:42");
                });
    }

    @Test
    void 外部ライブラリのクラスはスキャンだけでは登録されずBeanメソッドで構成する() {
        runner.withUserConfiguration(LibraryScan.class)
                .run(context -> assertThat(context.getBeansOfType(LibraryPaymentClient.class)).isEmpty());

        runner.withUserConfiguration(PaymentRegistration.SalesOnly.class,
                        PaymentRegistration.ExternalLibrary.class)
                .run(context -> {
                    assertThat(context.getBeansOfType(LibraryPaymentClient.class)).hasSize(1);
                    assertThat(context.getBean(OrderService.class).authorize("42")).isEqualTo("SDK:42");
                });
    }

    @Test
    void Profileが不一致なら候補は零件で有効にすると登録される() {
        var setup = runner.withUserConfiguration(PaymentRegistration.SalesOnly.class,
                PaymentRegistration.ProfileGateway.class);
        setup.run(context -> assertMissingGateway(context.getStartupFailure()));

        setup.withPropertyValues("spring.profiles.active=test-payment")
                .run(context -> assertThat(context.getBean(OrderService.class).authorize("42"))
                        .isEqualTo("STUB:42"));
    }

    private void assertMissingGateway(Throwable startupFailure) {
        assertThat(startupFailure).isNotNull();
        assertThat(startupFailure).hasRootCauseInstanceOf(NoSuchBeanDefinitionException.class);
        var cause = (NoSuchBeanDefinitionException) startupFailure.getCause();
        assertThat(cause.getBeanType()).isEqualTo(PaymentGateway.class);
        assertThat(cause.getNumberOfBeansFound()).isZero();
    }

    @Configuration(proxyBeanMethods = false)
    @ComponentScan(basePackageClasses = PlainCardPaymentGateway.class)
    static class PlainScan {
    }

    @Configuration(proxyBeanMethods = false)
    @ComponentScan(basePackageClasses = LibraryPaymentClient.class)
    static class LibraryScan {
    }
}
Tests run: 7, Failures: 0, Errors: 0, Skipped: 0

コードレビューで伝えるコメント例

OrderServiceが要求するPaymentGatewayの候補が0件でした。CardPaymentGatewayには@Componentがありますが、SalesOnlyの探索対象は注文側だけです。SalesAndIntegrationで連携側を探索対象に加え、同じ注文サービスがCARD:42を返すことまで確認します。

単に「@Serviceを付けてください」と書くより、必要な型、現在足りない登録、候補となる設計を示すと、修正理由が伝わります。

提出前のセルフチェック

レビュー前に確認すること

  • 要求された型をログから特定したか
  • 要求元のコンストラクタ引数を確認したか
  • 実装クラスが存在するか
  • 役割に合うBean登録アノテーションがあるか
  • @Beanメソッドが読み込まれるか
  • 起動クラス配下のスキャン範囲か
  • ProfileやConditionalの条件を満たすか
  • 候補0件と複数件を区別したか
  • required=falseで隠していないか
  • テストの読み込み範囲に合っているか

SpringのDIを体系的に確認する参考書

DIエラーはアノテーションの暗記だけでは解決しにくく、SpringコンテナがBeanを登録し、型を使って依存関係を解決する流れを理解すると切り分けやすくなります。

書籍「作って学ぶ Spring Boot入門」の表紙
商品画像:Amazon.co.jp
PR Java新人・若手向け

作って学ぶ Spring Boot入門

多田 真敏 (著)

Spring Bootを、動くWebアプリを作りながら覚える。

Controller、画面、DB連携などを一つのアプリとして実装できます。Java基礎からSpringの現場へ進む橋渡しに向く一冊です。

  • Spring Bootを手を動かして学びたい
  • Webアプリ開発の流れをつかみたい

当サイトはAmazonアソシエイト・プログラムの参加者です。価格・在庫・配送条件はAmazonでご確認ください。

この記事とあわせて読みたい

関連記事NoSuchBeanDefinitionExceptionの原因|XML・@Serviceがあるのに登録されないとき 要求する型とBean登録、読み込む設定を整理します。 記事を読む 関連記事Spring Bootの@Qualifierと@Primaryの違いは?Beanが複数ある時の使い分け 同じ型のBeanが複数ある場合に、注入先を選ぶ判断軸を整理します。 記事を読む 関連記事Springの@Component・@Service・@Repositoryの違い|どれを付けるべき? Bean登録アノテーションをクラスの責務に合わせて選ぶ方法です。 記事を読む

まとめ

Spring BootのNo qualifying bean of typeは、要求された型に合うBeanをSpringが見つけられないときに発生します。ログから要求型と要求元を特定し、実装、アノテーション、@Bean、スキャン範囲の順で確認します。

候補が0件なのか、複数あって選べないのかも分けてください。起動だけ通すために任意依存やnewへ逃げず、その依存が必須か、どの実装を使うかを設計として決めることが、現場で再発しない修正につながります。

Autowiredによる型解決の基本はSpring Framework公式ドキュメントでも確認できます。

-実装・エラー解決
-,