Field testDao in com.service.TestService required a bean of type
‘com.dao.TestDao’ that could not be found.注入bean失败!!
重点一:
注入失败bean的包是否是启动类的同包目录或是子包目录;
说明:spring boot 默认的扫描路径是启动类当前的包和子包,所以我们在创建项目的时候需要注意,启动类Application需要在最底层
如果已经不能修改路径:
一.添加@ComponentScan(“com.dao”)注解
项目会扫描com.dao同包和子包下的所有@@Component标记过的bean;
重点二:
在多模块项目的情况下,如果Controller层注入失败bean是接口需要注意是在这个Controller所在的模块中是否能够访问接口实现类
说明:spring 无法注入没有实现类的接口
<dependency>
<groupId>com.example</groupId><!-- 模块的共同包名 -->
<artifactId>domain</artifactId><!-- 接口实现类所在的模块 -->
<version>0.0.1-SNAPSHOT</version>
</dependency>
重点三:
@Autowired注入的对象是否是有参构造
说明:
如果以上都能做到即使这样写,也可以启动:
接口:Spring 无法注入有参构造对象
public interface HelloInterface {
String hello(String parameter);
}
实现接口的实现类
@Service
public class HelloInterfaceImp implements HelloInterface {
@Override
public String hello(String parameter) {
return "hello"+parameter;
}
调用接口的Controller层
@RestController
public class HelloServer {
@Autowired
private HelloInterface helloInterface;
@GetMapping("/hello")
public String helloMethod(@RequestParam("parameter") String parameter) {
return helloInterface.hello(parameter);
}
}