目次
【Spring Boot】NoSuchBeanDefinitionExceptionの対処法
要約
- エラーの概要: SpringのDIコンテナが、注入しようとしているBeanを見つけられない。
- 主な原因:
- Bean対象クラスに
@Service,@Componentなどのアノテーションが付与されていない @ComponentScanでスキャン対象パッケージが誤っている
- Bean対象クラスに
- 修正方法のポイント:
- 正しいアノテーションを付与し、パッケージスキャン設定を見直す
エラー例
@RestController
public class SampleController {
@Autowired
private SomeService someService; // Beanが見つからない
@GetMapping("/test")
public String test() {
return someService.doSomething();
}
}
org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.example.SomeService' available
SomeServiceクラスに@Serviceなどが付与されていない@ComponentScanの対象外にクラスが存在
修正例
@Service
public class SomeService {
public String doSomething() {
return "Hello from SomeService!";
}
}
@SpringBootApplication
@ComponentScan(basePackages = "com.example") // スキャン対象を正しく指定
public class MyApplication {
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
}
または、SpringはXMLでも指定が可能です。
以下のように指定することで、XML上でもComponentScanの対象を指定できます。
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!-- base-package属性でコンポーネントスキャンするパッケージを指定 -->
<context:component-scan base-package="com.example.service" />
<!-- 必要に応じて他のBean定義や設定を追加 -->
</beans>
詳細
なぜそうなるのか?
- Springでは、
@ComponentScanが指定したパッケージ以下にある@Component派生のクラス(@Service,@Repository,@Controllerなど)を自動検出してBeanを作成します。 - Beanとして登録してほしいクラスがスキャン範囲外にあったり、アノテーションを付与していない場合はBeanとして認識されず、
NoSuchBeanDefinitionExceptionとなります。
仕組みのポイント
@ComponentScanは指定パッケージ以下のみスキャンするため、パッケージがズレると一切認識されません。- クラスに
@Serviceや@Componentを付与していないと、Springは「ただのクラス」とみなし、管理しません。
