首页 > 解决方案 > Spring-boot 似乎没有获取存储库

问题描述

我不能在我的服务类中使用我的 CrudRepository。我可以创建存储库,但是当我将它自动连接到我的服务类时,我收到了这个错误:

com.test.service.testService 中构造函数的参数 0 需要找不到类型为“com.test.repository.TestRepository”的 bean。

行动:

考虑在您的配置中定义“com.test.repository.TestRepository”类型的 bean。

对于很多人来说,这似乎是一个大问题。我尝试了各种方法,例如@ComponentScan、@EnableAutoConfiguration、@EnableJpaRepositories,但都没有奏效。

主应用:

@ComponentScan ({"com.test.repository", "com.test.controller","com.test.service","com.test.model"})
@EnableJpaRepositories
@EnableAutoConfiguration(exclude = {DataSourceAutoConfiguration.class})
public class Application {
    public static void main(String[] args){
        SpringApplication.run(Application.class);
    }
}

服务:


    public testService(TestRepository testRepository) {
        this.testRepository= testRepository;
    }

存储库

package com.test.TestRepository;


import com.test.model.Item;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface TestRepository extends CrudRepository<Item, Long> {
}

POM.xml

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
        <version>2.1.6.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
        <version>2.1.6.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>com.h2database</groupId>
        <artifactId>h2</artifactId>
        <scope>runtime</scope>
    </dependency>
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <version>1.18.8</version>
    </dependency>
</dependencies>

我希望存储库是自动装配的并且功能齐全。

标签: javamavenspring-bootintellij-idea

解决方案


尝试这个:

@EnableJpaRepositories(basePackages = {"com.test"})

推荐阅读