【问题标题】:Spring Repositories with different profiles具有不同配置文件的 Spring 存储库
【发布时间】:2021-11-02 09:24:06
【问题描述】:

我有两个不同的配置文件,并希望为此配置文件有两个不同的存储库。但它是一个实体的存储库,只是在查询中具有不同的条件。

我尝试这样做:

这是我的存储库基本接口:

public interface RepositoryBaseInterface extends CrudRepository<MyEntity, Long> {
    List<MyEntity> getEntities();
}

我有两个配置文件存储库:

@Repository
@Profile("profile1)
public interface ProfileRepository extends RepositoryBaseInterface {
    @Query("My query 1")
    List<MyEntity> getEntities();
}

还有一个:

@Repository
@Profile("profile2)
public interface ProfileRepository2 extends RepositoryBaseInterface {
    @Query("My query 2")
    List<MyEntity> getEntities();
}

当我使用这个存储库时我有课:

@Service
@RequiredArgConstructor
public class UseRepository{

  RepositoryBaseInterface repository;

  public List<MyEntity> getMyEntities() {
     return repository.getEntities();
  }
}

我预计当我有两个活动配置文件之一时,它将被选择两个 ProfilesRepositories 之一,但我看到只有 RepositoryBaseInterface 正在使用并且我收到错误

Error creating bean with name RepositoryBeanInterface
IllegalArgumentException, No property getEntities found for type MyEntity

如何解决此问题并根据我的活动配置文件使用一个或另一个存储库?

【问题讨论】:

    标签: spring-profiles spring-repositories


    【解决方案1】:

    我理解我的错误。我们的基础接口应该没有任何扩展。但它的实现应该是。

    所以我有

        public interface RepositoryBaseInterface {
           List<MyEntity> getEntities();
        }
    

    还有两个Profile接口:

        @Repository
        @Profile("profile1)
        public interface ProfileRepository extends RepositoryBaseInterface, CrudRepository<MyEntity, Long> {
    
          @Query("My query 1")
          List<MyEntity> getEntities();
    }
    
        @Repository
        @Profile("profile2)
        public interface ProfileRepository2 extends RepositoryBaseInterface, CrudRepository<MyEntity, Long> {
    
          @Query("My query 2")
          List<MyEntity> getEntities();
    }
    

    【讨论】:

      猜你喜欢
      • 2016-12-17
      • 1970-01-01
      • 2015-06-16
      • 2019-05-25
      • 2015-08-06
      • 2014-02-03
      • 1970-01-01
      • 1970-01-01
      • 2018-05-15
      相关资源
      最近更新 更多