LoginSignup
0
0

More than 1 year has passed since last update.

Spring BootでNo qualifying bean of typeが発生した場合

Last updated at Posted at 2022-08-01

事象

普段、kotlinでSpring Bootを使って開発しています。
そこで、新しいクラスを作成してJUnitでテストをすると以下のエラーが発生しました。(エラー内容をメモしてなかったのでごく一部になります)

No qualifying bean of type ...

どうやら、「BeanFactory(というSpringのDIコンテナとして中心的な役割を果たすクラス)が、定義が見つからないインスタンスの要求を受けた時にこの例外が投げられるらしいです。
参考:https://qiita.com/NagaokaKenichi/items/058a7243bd2948de7553

原因

その1:アノテーションがついてない

対象クラス(今回は新しく作成したクラス)にアノテーションがついてないため、エラーとなりました。

以下のようなアノテーションを状況に応じて追加するとよさそうです。

@Component
@Controller
@Service
@Repository

その2:パッケージ構成

起点となるパッケージの管理下に対象クラスが存在しないため、エラーとなりました。

@ComponentScan(
    basePackages = [
        ...
    ],
    excludeFilters = [
        ComponentScan.Filter(
            ComponentScan.Filter(
            type = FilterType.ASSIGNABLE_TYPE,
            classes = [
                ...
            
            classes = [
                ...
            ]
        )
    ]
)

起点となるパッケージのクラスに上記の、basePackagesに対象にしたいパッケージを追加するとよさそうです。
しかし、追加したパッケージのクラスの一部に管理外のクラスがあるとDIできないため、そういう場合はexcludeFiltersに対象外にしたいクラスを記述するとよさそうです。記入例:SampleClass::class

まとめ

他にも原因があると思いますが、とりあえず自分の環境で発生したパターンは以上になります。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0