How to make instance of CrudRepository interface during testing in Spring?

后端 未结 4 1009
旧时难觅i
旧时难觅i 2021-02-07 08:53

I have a Spring application and in it I do not use xml configuration, only Java Config. Everything is OK, but when I try to test it I faced problems wi

4条回答
  •  渐次进展
    2021-02-07 09:01

    You cant use repositories in your configuration class because from configuration classes it finds all its repositories using @EnableJpaRepositories.

    1. So change your Java Configuration to:
    @Configuration
    @EnableWebMvc
    @EnableTransactionManagement
    @ComponentScan("com.example")
    @EnableJpaRepositories(basePackages={"com.example.jpa.repositories"})//Path of your CRUD repositories package
    @PropertySource("classpath:application.properties")
    public class JPAConfiguration {
      //Includes jpaProperties(), jpaVendorAdapter(), transactionManager(), entityManagerFactory(), localContainerEntityManagerFactoryBean()
      //and dataSource()  
    }
    
    1. If you have many repository implementation classes then create a separate class like below
    @Service
    public class RepositoryImpl {
       @Autowired
       private UserRepositoryImpl userService;
    }
    
    1. In your controller Autowire to RepositoryImpl and from there you can access all your repository implementation classes.
    @Autowired
    RepositoryImpl repository;
    

    Usage:

    repository.getUserService().findUserByUserName(userName);

    Remove @Repository Annotation in ArticleRepository and ArticleServiceImpl should implement ArticleRepository not ArticleService.

提交回复
热议问题