0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

[エラー][Spring Boot] インジェクトするBeanが複数存在する

Posted at

MockitoのgetBeanName()にて、以下のような例外が発生した。

Caused by: java.lang.IllegalStateException:
Unable to register mock bean <Hoge> expected a single matching bean to replace but found [<Class1>, <Class2>]

該当クラスの設定を確認してみる。

HOGE.class
// インターフェース定義
public interface Hoge {
}
Class1.class
// 実装クラス1
@Service
public class Class1 implements Hoge {
}
Class2.class
// 実装クラス2
@Service
public class Class2 implements Hoge {
}

以下は利用側のテストクラス。

HogeSpec.class
// テストクラス
@SpringBootTest
public class HogeSpec extends Specification {
    @MockBean
    Hoge hoge;
}

同じHogeインターフェースを実装したClass1Class2が、共に@ServiceアノテーションによってDIコンテナに登録されてしまっている。
そのため、どちらのBeanをインジェクトすれば良いかが判断できずにエラーが発生する。
Class1Class2どちらかのクラスをコンポーネントスキャン対象から外す(@Service)必要がある。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?