我正在使用一个简单的 Spring Boot 应用程序,我想使用 Hibernate 连接我的数据库。我无法将我的存储库类注入(inject)到我的 Controller 类中。请帮忙。但是,当我删除导致问题的代码时,我的应用程序能够扫描每个组件并且工作正常。我已经通过 Eclipse 创建了我的代码。
我的入门类(class)
package spring.starter;
@SpringBootApplication
@ComponentScan(basePackages = "spring")
public class Starter {
public static void main(String args[]) {
ApplicationContext ctx = SpringApplication.run(Starter.class, args);
}
}
我的 Controller 类
package spring.controller;
@RestController
@RequestMapping("/app")
public class AdminController {
/*@Autowired
private AdminService service;*/
@Autowired
@Qualifier("adminRepository")
private AdminRepository adminRepository;
@GetMapping("/admin")
public List<Admin> getAllAdmin() {
return adminRepository.findAll();
}
}
我的存储库类:对于这个类,我尝试删除两个注释,但这也不起作用。
package spring.repository;
@Repository
@Qualifier("adminRepository")
public interface AdminRepository extends JpaRepository<Admin, Integer>{
}
异常跟踪
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [spring.repository.AdminRepository] found for dependency [spring.repository.AdminRepository]: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true), @org.springframework.beans.factory.annotation.Qualifier(value=adminRepository)}
at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoMatchingBeanFound(DefaultListableBeanFactory.java:1406) ~[spring-beans-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1057) ~[spring-beans-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1019) ~[spring-beans-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:566) ~[spring-beans-4.3.2.RELEASE.jar:4.3.2.RELEASE]
... 19 common frames omitted
最佳答案
ComponentScan
注释未检测到 Spring Data JPA 存储库。对于他们,您必须提供注释
@EnableJpaRepositories(basePackages = "spring")
或者您更改 SpringBootApplication
注释如下:
@SpringBootAnnotation(scanBasePackages = "spring")
这将涵盖 ComponentScan
以及 EnableJpaRepositories
的自定义包配置。
在其中一项更改之后,您还可以删除 @Repository
来自存储库。该注释不适用于 Spring Data JPA 存储库接口(interface),并且对它们没有影响。
关于spring-boot - 未找到依赖项 : Spring Boot 的合格 bean 类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47854432/