Spring JPA Data Repository failed to create bean for interface that extends CrudRepository

11,436

Use basePackages in EnableJpaRepositories:

@Configuration
@EnableJpaRepositories(basePackages = "edu.sjsu.models")
@EnableTransactionManagement
public class JpaConfig { ... }

By default, EnableJpaRepositories will scan the package of the annotated configuration class for Spring Data repositories. Since, i'm guessing, your configuration and repository classes are in different packages, you should tell Spring Data JPA which base packages to scan in order to find JPA repositories.

Share:
11,436
amit rakesh
Author by

amit rakesh

Updated on June 08, 2022

Comments

  • amit rakesh
    amit rakesh almost 2 years

    I am facing problems working with Spring JPA Repositories. I have created:

    • a basic user domain class (@Entity),
    • an interface UserDao which extends CrudRepository
    • and a service layer implementation.

    When I run the project, it fails because of bean creation exception of UserDao. As far as I understand it is the responsibility of Spring JPA repositories to create the bean for this interface (because it extends CrudRepository) and inject it wherever it is required.

    This is the error I am getting:

    WARN : org.springframework.web.context.support.AnnotationConfigWebApplicationContext - Exception encountered during context initialization - cancelling refresh attempt org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'UserController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private edu.sjsu.services.UserService edu.sjsu.controllers.UserController.userService; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userServiceImpl': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: edu.sjsu.models.UserDao edu.sjsu.services.UserServiceImpl.userDao; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [edu.sjsu.models.UserDao] 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.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:334)

    UserDao.Java:

    package edu.sjsu.models;
    
    import org.springframework.data.jpa.repository.JpaRepository;
    import org.springframework.data.repository.CrudRepository;
    
    public interface UserDao extends CrudRepository<User, Long> {}
    

    RootConfig.Java:

    @Configuration
    @ComponentScan(basePackages={"edu.sjsu"}, excludeFilters={@Filter(type=FilterType.ANNOTATION, value=EnableWebMvc.class)})
    @Import(JpaConfig.class)
    public class RootConfig {}
    

    JpaConfig.java I think I don't even need this if using Spring JPA but still i have created this config class following guides and tutorials.

    @Configuration
    @EnableJpaRepositories
    @EnableTransactionManagement
    public class JpaConfig {
    
        @Bean
        public DataSource dataSource() {
            EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder();
            return builder.setType(EmbeddedDatabaseType.HSQL).build();
        }
    
        @Bean
        public EntityManagerFactory entityManagerFactory() {
    
            HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
            vendorAdapter.setGenerateDdl(true);
    
            LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
            factory.setJpaVendorAdapter(vendorAdapter);
            factory.setPackagesToScan("edu.sjsu");
            factory.setDataSource(dataSource());
            factory.afterPropertiesSet();
    
            return factory.getObject();
        }
    
        @Bean
        public PlatformTransactionManager transactionManager() {
    
            JpaTransactionManager txManager = new JpaTransactionManager();
            txManager.setEntityManagerFactory(entityManagerFactory());
            return txManager;
        }   
    
    }
    

    Let me know if you require other config and java classes to understand the situation.

  • amit rakesh
    amit rakesh about 8 years
    I have explicitly set packages to scan as factory.setPackagesToScan("edu.sjsu");
  • Ali Dehghani
    Ali Dehghani about 8 years
    That's for your entities. Those are annotated with @Entity.
  • amit rakesh
    amit rakesh about 8 years
    It worked. One additional thing that I had to do is to remove additional dependency hibernate-jpa-2.0-api from pom because <groupId>org.hibernate</groupId> <artifactId>hibernate-entitymanager</artifactId> was already compiling hibernate-jpa-2.1-api Thanks Ali
  • Admin
    Admin over 7 years
    Ali - Could you please guide on this issue stackoverflow.com/questions/39305162/…?