【问题标题】:spring data mongodb create repository implementationspring data mongodb创建存储库实现
【发布时间】:2013-12-31 12:47:46
【问题描述】:

我遇到了存储库 bean 定义的问题。首先,我不喜欢仅将存储库定义为接口并且不编写自己的实现的新样式。

所以我在写简单的界面:

public interface UserRepo {

  Member findByUsername(String username);

  Member findByEmail(Email email);

  Institution save(Institution institution);

  User save(User user);
}

正如您所见,该接口没有扩展任何 spring 数据接口,接下来我将为该接口创建自己的实现:

public class UserRepoImpl extends AbstractMongoQuerydslRepo<Member> implements UserRepo {

  private static final Logger LOG = LoggerFactory.getLogger(UserRepoImpl.class);

  private static final QMember memberQuery = QMember.member;
  private final PathBuilder<Member> memberPath;

  @Autowired
  public UserRepoImpl(MongoOperations mongoOperations) {
    super(mongoOperations);
    Preconditions.checkNotNull(mongoOperations);
    memberPath = new PathBuilderFactory().create(Member.class);
  }

  …
}

所以该类的存储库实现后缀为 Impl,这是默认值 EnableMongoRepository 注释中的后缀。接下来,我添加我的配置:

@EnableMongoRepositories(basePackageClasses={UserRepo.class})
public class MongoTestContext extends AbstractMongoConfiguration{
  …
}

我有错误:

No qualifying bean of type [com.xxxxx.infrastructure.repo.UserRepo] 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)}

我的配置有什么问题?我还尝试在 UserRepository 和 UserRepositoryImpl 中添加 @Repository 注释,但它不起作用。我的 UserRepo 和 UserRepoImpl 也有相同的包。

【问题讨论】:

    标签: spring mongodb spring-data spring-data-mongodb


    【解决方案1】:

    我认为你在某种程度上抱有错误的期望。 @EnableMongoRepositories 注释的存在是为了准确激活您似乎不喜欢的自动存储库机制(我当然想听听这样做的原因)。因此,选择退出该机制后,您还可以退出所有配置要求和设置(例如默认的 Impl 后缀)。

    因此,如果您真的想自己实现所有这些东西(这实际上会让您成为我遇到的第一个坚持编写她实际上不需要的代码的开发人员),您只需要声明您的实现作为 Spring bean 的类 - 通过使用 @Component/@Repository 对其进行注释并让构造函数使用 @Autowired 注释,或者通过 XML 或 JavaConfig 手动声明 bean 定义。

    【讨论】:

    • 但是例如,如果您使用 DDD 规范创建应用程序,您将在您的 repo 中只有一些方法,也许不是所有的 crud 方法。因此,出于这个原因,我想编写自己的实现。也许我只需要阅读和更新而不是全部。
    猜你喜欢
    • 2019-01-29
    • 2017-02-09
    • 1970-01-01
    • 2014-09-11
    • 2015-02-13
    • 2016-12-30
    • 2012-04-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多