基于国家的Spring Boot依赖项注入

时间:2020-03-31 15:26:49

标签: java spring spring-boot dependency-injection

我正在尝试根据运行时哪个国家/地区调用我的端点来实现依赖项注入,因此我有以下设置。

public interface Client {
  void call(Data data);
} 

@Profile({"prod"})
public class ClientA implements Client {
  @Override
  public void call(Data data) {
    // implementations goes here
  }
}

@Profile({"dev"})
public class ClientB implements Client {
  @Override
  public void call(Data data) {
    // implementations goes here
  }
}

但是此设置现在已足够,因为这仅取决于应用程序在哪个环境上运行。我已经看过springs @Condition批注,但这似乎还不够。我想要实现的目的是能够在我的属性文件中定义一个属性,该文件定义了在运行时应初始化给定impl的国家/地区。像这样:

@Profile("${client.a.countries}")
public class ClientA implements Client {
  @Override
  public void call(Data data) {
    // implementations goes here
  }
}

,然后在我的application.propeties文件中定义client.a.countries=DE,GB,ES。有什么办法可以做到这一点?因此,当前端呼叫我的终结点时,我知道它从哪个国家呼叫,因此应该知道要使用哪个实现。我是否应该错误地追求这一点?我应该考虑进行某种Factory模式实现以实现我的目标吗?或者Spring可以实现吗?

1 个答案:

答案 0 :(得分:1)

我通过创建一个ClientRegistry解决了这个问题,所有客户都在该客户注册处注册了他们打算去的国家(一张地图左右)

public class ClientRegistry {
    private Map<String,Client> clients ;

    @Autowired
    public ClientRegistry(List<Client> clients) {

        this.clients = clients.stream().collect(Collectors.toMap(Client::getCountry, Function.identity() )) ;
    }

    public Client getClient(String country) {
        return clients.get(country);
    }
}

在客户端界面中,您必须添加getCountry

public interface Client
{
    void call(Data data);

    String getCountry();
}

现在,您可以选择让ClientRegistry实现Client函数并取消对相应Client的调用,或者在Cotroller中始终像clientRegistry.getClient(country).call(data)一样调用Client