MeWrite Docs

NoSuchBeanDefinitionException

Spring BootでBeanが見つからない場合に発生するエラー

概要

NoSuchBeanDefinitionExceptionは、Spring IoCコンテナに登録されていないBeanを注入しようとした場合に発生します。

エラーメッセージ

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

原因

  1. アノテーション不足: @Component等が付いていない
  2. コンポーネントスキャン外: スキャン対象パッケージに含まれていない
  3. 設定クラスの問題: @Configurationや@Beanが不足
  4. 循環依存: Bean同士が相互に依存

解決策

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

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
// サービスクラス
@Service
public class UserService {
    // ...
}

// リポジトリ
@Repository
public class UserRepository {
    // ...
}

// 汎用コンポーネント
@Component
public class MyComponent {
    // ...
}

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

1
2
3
4
5
6
7
@SpringBootApplication
@ComponentScan(basePackages = {"com.example", "com.other"})
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

3. 設定クラスでBeanを定義

1
2
3
4
5
6
7
8
@Configuration
public class AppConfig {

    @Bean
    public UserService userService() {
        return new UserService();
    }
}

4. 条件付きBeanの確認

1
2
3
4
5
@Service
@ConditionalOnProperty(name = "feature.enabled", havingValue = "true")
public class FeatureService {
    // feature.enabled=true の時のみ登録
}

5. プロファイルを確認

1
2
3
4
5
@Service
@Profile("production")
public class ProductionService {
    // productionプロファイルでのみ有効
}
1
2
# プロファイル指定で起動
java -jar app.jar --spring.profiles.active=production

6. インターフェースの実装を確認

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
// インターフェース
public interface UserService {
    User findById(Long id);
}

// 実装クラスに@Serviceが必要
@Service
public class UserServiceImpl implements UserService {
    @Override
    public User findById(Long id) {
        // ...
    }
}

7. @Qualifierで明示

1
2
3
@Autowired
@Qualifier("primaryUserService")
private UserService userService;

Java の他のエラー

最終更新: 2025-12-09