控制器

时间:2016-07-29 07:21:05

标签: spring spring-data spring-data-jpa spring-bean

我有spring-boot-starter-data-jpaspring-boot-starter-web。我尝试使用List<Project>mysql加载Spring jpa,但在控制器中看到BeanCreationException。

  

org.springframework.beans.factory.BeanCreationException:使用名称&#39; controller&#39;创建bean时出错:注册自动连接的依赖项失败;嵌套异常是org.springframework.beans.factory.BeanCreationException:无法自动装配字段:private com.project.data.spring_jpa.ProjectRepository com.project.application.Controller.repository;嵌套异常是org.springframework.beans.factory.NoSuchBeanDefinitionException:找不到类型为[com.project.data.spring_jpa.ProjectRepository]的限定bean依赖:预期至少有1个bean可以作为此依赖项的autowire候选者。依赖注释:{@ org.springframework.beans.factory.annotation.Autowired(required = true)}

Controller.java:

...
@RestController
public class Controller {

    ...

    @Autowired 
    private ProjectRepository repository;


    private ProjectAccessor projectAccessor = manager.createAccessor(ProjectAccessor.class);

    public void setRepository(ProjectRepository repository){
        this.repository = repository;
    }

    @RequestMapping("/test")
    @ResponseBody
    public List<Project> test() {


        System.out.println("mysql test");

        return repository.findAll();
    }

    ...

ProjectRepository.java:

public interface ProjectRepository extends CrudRepository<Project, Long>{
     List<Project> findAll();
}

2 个答案:

答案 0 :(得分:0)

您是否在 @Repository

上撰写了ProjectRepository注释?
@Repository
public interface ProjectRepository extends CrudRepository<Project, Long>{
     List<Project> findAll();
}

确保使用 @EnableJpaRepositories

在配置上启用了JpaRepository

答案 1 :(得分:0)

当我们没有指定在何处查找 JPA 存储库时,我们通常会收到此异常。 所以提到@EnableJpaRepositories("your repository package"),在那里你指定@Configuration 或@SpringBootApplication。 它会正常工作。