Spring - 在运行时解决依赖关系

时间:2018-04-23 18:04:19

标签: java spring dependency-injection spring-data

我用Spring Data撰写Customer个应用。我有两个实体:MerchantCustomerRepository。我还有两个相应的存储库和服务:MerchantRepositoryCustomerServiceMerchantServiceCustomerServiceMerchantServiceCustomerRepository中的逻辑非常相似,但与不同的存储库相关(相应地MerchantRepositoryclass Customer { // ... } class Merchant { // ... } interface CustomerRepository extends CrudRepository<Customer, Long> { // ... } interface MerchantRepository extends CrudRepository<Merchant, Long> { } class CustomerService { private CommonHelper helper; void method() { helper.commonMethod(); // ... } } class MerchantService { private CommonHelper helper; void method() { helper.commonMethod(); // ... } } class CommonHelper { private CrudRepository repository; public CommonHelper(CrudRepository repository) { this.repository = repository; } public void commonMethod() { repository.findAll(); // ... } } )。所以看起来或多或少是这样的:

CommonHelper

我想创建第三类,让它调用它new以避免代码重复并在那里放置通用逻辑(操作相同但使用不同的存储库)。但后来我需要两个独立的实例和两个不同的存储库。当然我可以使用Spring来实例化它,但是有更多的{{1}}方法来实现相同的目标吗?

1 个答案:

答案 0 :(得分:0)

您可以为CommonHelper提取一个抽象类,并定义两个实现它的bean:一个用于Merchant关注,另一个用于客户关注。
接口可以是通用的,以便能够根据实现来调整API类型。

例如:

public abstract class BaseService<T, K> {

    private CrudRepository<T, K> repository;

    public BaseService(CrudRepository<T, K> repository){
       this.repository = repository;
    }

    T commonMethod(K key){
        T object = repository.findById(key);
        // other processing...
    }
}

实施:

@Service
@Qualifier("customerBaseService") 
public class CustomerBaseService extends BaseService<Customer, Long> {
    public CustomerBaseService (CustomerRepository repository){
      super(repository);
    }
}

@Service
@Qualifier("merchantBaseService") 
public class MerchantBaseService extends BaseService<Merchant, Long> {
    public MerchantBaseService (MerchantRepository repository){
      super(repository);
    }
}

然后通过指定与。匹配的限定符,在CustomerService或MerchantService中注入合适的。