首页 > 解决方案 > 如何将位于依赖项中的自动实现的存储库注册为 bean?

问题描述

我有一个具有模块A项目依赖项的模块B

A的build.gradle

dependencies {
  ....
  compile project(":B")
}

在 module B,我有这个接口:

@Repository
public interface MyRepo extends CrudRepository<User, String> {
    //some methods
} 

在 module A,我有这个配置类:

@Configuration
public class MyConfig {    

  @Bean
  public MyRepo provideMyRepo() {
      //???
  }

}

如何MyRepo在模块中导出 bean A

我试过使用@ComponentScanand @EnableJpaRepositories

@Configuration
@EnableJpaRepositories(basePackageClasses = MyRepo.class)
public class MyConfig {    

  @Autowired
  public MyRepo myRepo;

}

但是找不到bean:

org.springframework.beans.factory.NoSuchBeanDefinitionException:没有找到符合条件的依赖项

标签: springdependency-injectionspring-data

解决方案


您不需要该存储库的新配置,因为它已经在 Spring 中注册。您可以将其直接注入A模块中的客户端类中:

@Component
public class MyComponent {    
  @Inject
  private MyRepo myRepo;

  // your code using myRepo

}

如果 Spring 说它找不到 bean,您需要检查您拥有的自动装配配置,因此检查您的扫描路径是否包含存储库类B(使用 @ComponentScan 或更改)

这个例子


推荐阅读