首页 > 解决方案 > 带有注解@Primary和@Secondary的SpringBoot Bean依赖注入

问题描述

我有一个存储库接口和两个实现它的类,一个是缓存存储库,另一个是 MongoDB 存储库。

public interface Repository {}

@Primary
@Component
public class CacheRepo implement Repository {}

@Component
public class MongoDBRepo implement Repository {}

获取项目的理想过程是使用缓存存储库检查它是否存在于缓存中,如果不存在,请使用 MongoDB存储库@Primary,我的CacheRepo类上有一个,并且在我的服务中依赖注入存储库接口,但我怎么还能使用与MongoDBRepo缓存中未找到项目相同的注入实例?有没有类似@Secondary注释的东西?

标签: spring-bootdependency-injectionjavabeans

解决方案


您要实施的是Repository Pattern

这是一个简单的实现方法

public interface MyRepository {
  Optional<MyClass> findById(Long id);
}

然后你将有 3 个实现。这就是逻辑所在。

@Repository
@Qualifier("db")
public interface MyDbRepository extends MyRepository, CrudRepository<MyClass, Long>{
}

@Component
@Qualifier("cache")
public class MyCacheRepository implements MyRepository {
  public Optional<MyClass> findById(Long id){
    return Optional.empty();
  }
}

// This is the key
@Component
@Primary
public class MyDataSource implements MyRepository {

  @Autowire
  @Qualifier("db")
  private MyRepository dbRepo;

  @Autowire
  @Qualifier("cache")
  private MyRepository cacheRepo;

  public Optional<MyClass> findById(Long id){
    Optional<MyClass> myResponse = cacheRepo.findById(id);
    if(myResponse.isPresent()){
      return myResponse;
    } else {
      myResponse = dbRepo.findById(id);
      if(myResponse.isPresent){
        // Update your cache here
      }
      return myResponse;
    }
  }

}

推荐阅读