0
votes

I have spring-boot-starter-data-jpa and spring-boot-starter-web. I try load List<Project> from mysql using Spring jpa but get bellow BeanCreationException in controller.

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'controller': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.project.data.spring_jpa.ProjectRepository com.project.application.Controller.repository; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.project.data.spring_jpa.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)}

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
can you post your applicationContext.xml?amicoderozer
I got correct way from you. I created AppConfig.java class with @Configuration @EnableJpaRepositories("com.project.data.spring_jpa.repositories") class level annotations and exceptions gone.Edgaras Karka
my guess was that you missed the <context:component-scan base-package="com" /> from applicationContext.xml or your config classamicoderozer

2 Answers

0
votes

Did you write @Repository annotation on ProjectRepository

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

Do make sure you enabled JpaRepository on your configuration using @EnableJpaRepositories

0
votes

We get this exception usually when we don't specify where to look for the JPA repositories. So mention @EnableJpaRepositories("your repository package") where you specify @Configuration or @SpringBootApplication. It will work fine.