Spring Boot 中 JPA 存储库的“没有合格的 bean 类型”

2022-09-01 08:55:23

我正在用Spring Boot实现Rest API。由于我的实体类来自另一个包的包,因此我必须使用注释来指定它。另外,我曾经指定定义 JPA 存储库的包。以下是我的项目:EntityScanEnableJpaRepositories

enter image description here

//Application.java

@Configuration
@EnableAutoConfiguration
@ComponentScan
@EntityScan("org.mdacc.rists.cghub.model")
@EnableJpaRepositories("org.mdacc.rists.cghub.ws.repository") 

在我的控制器类中,我有一个自动连接的SeqService对象。

//SeqController.java

@Autowired private SeqService seqService;

@RequestMapping(value = "/api/seqs", method = GET, produces = APPLICATION_JSON_VALUE)
public ResponseEntity<List<SeqTb>> getSeqs() {
    List<SeqTb> seqs = seqService.findAll();
    return new ResponseEntity<List<SeqTb>>(seqs, HttpStatus.OK);
}

SeqService是一个接口,我从中为该创建了一个Bean类。在 I 自动连接 JPA 存储库中:SeqServiceBeanSeqServiceBean

// SeqServiceBean.java

@Autowired private SeqRepository seqRepository;

@Override
public List<SeqTb> findAll() {
    List<SeqTb> seqs = seqRepository.findAll();
    return seqs;
}

//SeqRepository.java

@Repository
public interface SeqRepository extends JpaRepository<SeqTb, Integer> {

    @Override
    public List<SeqTb> findAll();

    public SeqTb findByAnalysisId(String analysisId);
}

但是,由于以下错误,应用程序无法启动:

Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.mda.rists.cghub.ws.repository.SeqRepository] 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)}
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:1373) ~[spring-beans-4.2.5.RELEASE.jar:4.2.5.RELEASE]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1119) ~[spring-beans-4.2.5.RELEASE.jar:4.2.5.RELEASE]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1014) ~[spring-beans-4.2.5.RELEASE.jar:4.2.5.RELEASE]
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:545) ~[spring-beans-4.2.5.RELEASE.jar:4.2.5.RELEASE]

我不明白这个错误。它与合格的豆子有什么关系?


答案 1

您正在扫描 .没有包。因此,请改用以下命令:EnableJpaRepositoriesorg.mdacc.rists.cghub.ws.repository

@EnableJpaRepositories("org.mda.rists.cghub.ws.repository") 

Spring Boot不需要任何特定的代码布局即可工作,但是,有一些最佳实践可以帮助您。查看 Spring Boot 文档,了解构建代码的最佳实践。


答案 2

推荐