简体   繁体   中英

Spring boot dependency inject based on country

I am trying to achieve dependency injection based on which country calls my endpoint on runtime so I have the following setup.

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
  }
}

But this setup is now enough since this only depends on which environment the application is running on. I have looked on springs @Condition annotation but it does not seem to be enough. What I want to achieve it to be able to define a property in my properties file which defines which countries a given impl should be initilized for on runtime. So something like:

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

and then in my application.propeties files I just define client.a.countries=DE,GB,ES . Is there any way of achieving this? So when the frontend calls my endpoint I know which country it is calling from and thereby should know which implementation to use. Am I a pursuing this wrongly should I be looking into doing some kind of Factory pattern implementation to achieve my goal or is it possible with Spring?

I solved this once by creating a ClientRegistry in which all Clients gets registred with the country they are intended for (a Map or so)

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);
    }
}

In the client Interface you have to add getCountry

public interface Client
{
    void call(Data data);

    String getCountry();
}

Now you have the option to let ClientRegistry implement the Client functions and delegete the calls to the appropriate Client or in the Cotroller you call the Client always like clientRegistry.getClient(country).call(data)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM