Spring NoSuchBeanDefinitionException存储库进入服务

时间:2016-07-14 20:51:49

标签: java spring hibernate

我刚刚使用Spring Boot V1.3.5设置了一个新项目,并且在尝试将存储库自动装入服务时,我不断收到NoSuchBeanDefinitionException。这很奇怪,因为我有其他项目设置方式相同,工作正常。

我的应用程序类。

package api;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);

        System.out.println("-------------------");
        System.out.println("The API is running.");
        System.out.println("-------------------");
    }
}

我的服务。

package api.services;

import api.entity.Project;
import api.repository.ProjectRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class ProjectService {

    @Autowired
    private ProjectRepository projectRepository;

    /**
     * Saves a project entity into the database.
     *
     * @param project Project
     * @return Project
     */
    public Project save(Project project) {

        return this.projectRepository.save(project);
    }
}

我的存储库。

package api.repository;

import api.entity.Project;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface ProjectRepository extends CrudRepository<Project, Integer> {

    Project findByName(String name);
}

现在我的服务被自动连接到我的控制器中,但由于某种原因,Spring似乎不喜欢我的存储库。

任何人都可以看到错误/遗失的内容吗?

感谢。

异常消息是:

Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private api.repository.ProjectRepository api.services.ProjectService.projectRepository; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [api.repository.ProjectRepository] 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)}

3 个答案:

答案 0 :(得分:4)

代码没有问题。 确保您有正确的依赖项。

有一次,我遇到了同样的问题,刚刚发现我正在注入一些 spring 数据依赖项,而不是包含其他依赖项集合的 spring-boot-starter-data-jpa ,而我的没有包括所有必要的。

所以说简单点,删除不必要的依赖项并在您的 pom.xml 中包含以下内容(如果您使用的是 maven)

<dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>

答案 1 :(得分:0)

尝试@Component而不是@Repository。

答案 2 :(得分:0)

好吧,检查一下设置方法相同的其他项目。首先,我只是注意到你使用了spring数据jpa,因此,注释@Repository不需要接口,因为spring boot会自动扫描它。最后,我认为您需要看到与您具有相同配置的项目。 spring-boot-sample-data-jpa

相关问题