MeWrite Docs

Spring: No qualifying bean of type

SpringでDI対象のBeanが見つからない際のエラー原因と解決策

概要

Spring DIコンテナで注入対象のBeanが見つからない、または複数見つかった際に発生するエラーです。

エラーメッセージ

``` org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type ‘com.example.UserService’ available ```

原因

  1. @Component 系アノテーション忘れ: Bean登録されていない
  2. コンポーネントスキャン範囲外: パッケージがスキャン対象外
  3. 複数の候補Bean: @Qualifier が必要
  4. 条件付きBeanの不一致: @ConditionalOn… の条件不成立

解決策

1. アノテーションを追加

```java @Service // または @Component, @Repository public class UserServiceImpl implements UserService { // … } ```

2. コンポーネントスキャンを確認

```java @SpringBootApplication @ComponentScan(basePackages = {“com.example”, “com.other”}) public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } } ```

3. 複数候補の場合は @Qualifier で指定

```java @Service @Qualifier(“primary”) public class UserServiceImpl implements UserService {}

@Service @Qualifier(“backup”) public class BackupUserService implements UserService {}

// 注入時 @Autowired @Qualifier(“primary”) private UserService userService; ```

4. @Primary で優先Beanを指定

```java @Service @Primary public class UserServiceImpl implements UserService {} ```

5. 条件付きBeanの確認

```java @Service @ConditionalOnProperty(name = “feature.enabled”, havingValue = “true”) public class FeatureService {}

// application.yml feature: enabled: true ```

よくある間違い

  • インターフェースにアノテーションを付ける(実装クラスに付ける)
  • テスト時に必要なBeanをMock化していない
  • application.propertiesの設定漏れ

関連エラー

関連エラー

Java の他のエラー

最終更新: 2025-12-10