Spring Boot @ComponentScanの使いどころ
@ServiceがInjectionできない
Spring Bootで以下のプログラムがコンパイルできなかった。
Controllerクラス
package com.sample.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import com.confront_them.bean.ResultBean; import com.confront_them.bean.ResultRequestBean; @Controller public class ResultController { @Autowired private ResultService resultService; @RequestMapping("/results") public String results(Model model) { ResultRequestBean requestbean = new ResultRequestBean(); ResultBean bean = new ResultBean(); resultService.execute(requestbean, bean); model.addAttribute("bean", bean); return "results } }
Serviceクラス
package com.sample.service; import org.springframework.stereotype.Service; import com.confront_them.bean.ResultBean; import com.confront_them.bean.ResultRequestBean; @Service public class ResultService { public void execute(ResultRequestBean requestbean, ResultBean bean) { bean.setHoge("hoge"); } }
エラーは以下の通り。
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'resultController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.sample.service.ResultService com.sample.controller.ResultController.resultService; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.sample.service.ResultService] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
対策
AutowiredしているのにScan対象のbeanがないと行っている。
@ComponentScanは記載されたControllerクラスと同じパッケージ配下のクラスしかScanしないらしく、それが原因でServiceクラスがみれていない。
なので以下のようにパッケージ名を変更したら、コンパイルできるようになった。
package com.sample.controller -> package com.sample; package com.sample.service; -> package com.sample;