Scrivio Interview library
DesignIntermediate7 min read · updated 12 November 2026

Design a payment router that selects one of several PaymentProvider beans by country at runtime, without a growing if-else block.

Each PaymentProvider bean declares the countries it supports. The router receives List<PaymentProvider> by injection and, in its constructor, builds an immutable Map from country to provider, failing fast at startup if two providers claim the same country or a required country has no provider. At runtime, routing is a single map lookup, and a new provider is added simply by adding a bean, without changing the router.

Why this question is asked

Payment routing is a classic place for an if-else chain to grow: if country is DE use Adyen, else if US use Stripe, and so on, edited by every team that adds a market. Each edit risks breaking a country nobody tested. Interviewers ask this design question to see whether we can use dependency injection to make the code open for new providers without changing it, and whether we think about the failure cases at startup rather than in production. In this answer, we will look at the if-else version and its problems, design the provider contract, build the router, add the startup checks, show how a new provider is added, and test it.

1The Starting Point and Its Problems

Here is the version we want to replace.

Java
@Service
class PaymentRouter {
private final StripeProvider stripe; private final AdyenProvider adyen; private final PayUProvider payu;
PaymentResult pay(Payment p) {
if (p.country().equals("US") || p.country().equals("CA")) return stripe.pay(p);
else if (p.country().equals("DE") || p.country().equals("NL")) return adyen.pay(p);
else if (p.country().equals("IN")) return payu.pay(p);
else throw new UnsupportedCountryException(p.country());
}
}

Every new provider means a new constructor parameter and a new branch in the router. The knowledge of which provider serves which country is split between the router and the providers. And mistakes only appear at runtime: if two branches claim the same country, the first one silently wins; if a country is missing, the first customer from that country gets an exception.

2Each Provider Declares Its Countries

We move the knowledge to where it belongs. The provider interface gets a method that says which countries the provider supports, using a small value type for countries so that typos are caught early.

Java
public interface PaymentProvider {
Set<CountryCode> supportedCountries();
PaymentResult pay(Payment payment);
}
@Component
class StripeProvider implements PaymentProvider {
public Set<CountryCode> supportedCountries() { return Set.of(CountryCode.US, CountryCode.CA); }
public PaymentResult pay(Payment p) { /* call Stripe */ }
}
@Component
class AdyenProvider implements PaymentProvider {
public Set<CountryCode> supportedCountries() { return Set.of(CountryCode.DE, CountryCode.NL); }
public PaymentResult pay(Payment p) { /* call Adyen */ }
}

The countries could equally come from configuration, for example payments.adyen.countries=DE,NL bound with @ConfigurationProperties, which lets operations move a country between providers without a code change. Either way, each provider owns its own claim.

3The Router Builds a Map at Startup

The router asks Spring for every provider by injecting List<PaymentProvider>, which gives every bean of that type, and turns the list into a lookup table once, in its constructor.

Java
@Service
class PaymentRouter {
private final Map<CountryCode, PaymentProvider> byCountry;
PaymentRouter(List<PaymentProvider> providers, PaymentProperties props) {
Map<CountryCode, PaymentProvider> map = new EnumMap<>(CountryCode.class);
for (PaymentProvider p : providers) {
for (CountryCode c : p.supportedCountries()) {
PaymentProvider previous = map.putIfAbsent(c, p);
if (previous != null) throw new IllegalStateException(
c + " is claimed by both " + name(previous) + " and " + name(p));
}
}
Set<CountryCode> missing = new HashSet<>(props.requiredCountries());
missing.removeAll(map.keySet());
if (!missing.isEmpty()) throw new IllegalStateException("No payment provider for " + missing);
this.byCountry = Collections.unmodifiableMap(map);
}
PaymentResult pay(Payment p) {
PaymentProvider provider = byCountry.get(p.country());
if (provider == null) throw new UnsupportedCountryException(p.country());
return provider.pay(p);
}
}
// Startup with Stripe {US, CA}, Adyen {DE, NL}: byCountry = {CA=Stripe, DE=Adyen, NL=Adyen, US=Stripe}
// pay(DE payment) -> AdyenProvider
Step throughBuilding the routing table and routing a payment
SpringPaymentRouterAdyenProvider
new PaymentRouter([Stripe, Adyen, PayU], props)
build country map, check duplicates and gaps
ready, or fail startup with a clear message
pay(DE): byCountry.get(DE)
pay(payment)
PaymentResult

6 messages in order. Play them, or step through them one at a time.

Notice that the routing method no longer knows any provider or country. It is one map lookup, constant time however many providers we add. The map is built once and made unmodifiable, so it is safe to read from many request threads without locking.

4Failing Fast at Startup

The two checks in the constructor are the most valuable part of the design. If a team adds a provider that also claims DE, the application refuses to start with a message such as "DE is claimed by both AdyenProvider and KlarnaProvider", in CI or at the first deployment, instead of silently routing German payments to whichever bean happened to come first. If a market the business requires, listed in payments.required-countries, has no provider, startup also fails. Both mistakes are found before a single customer payment is affected.

Sometimes two providers for one country is legitimate, for example a primary and a backup. In that case we make it explicit instead of allowing it by accident: the map holds an ordered list per country, sorted with @Order or a priority from configuration, and the router tries the next provider when the first is unavailable. The duplicate check then becomes a check that each priority is unique.

Step throughRouter start-up checks
  1. Inject every PaymentProvider beanList<PaymentProvider>
  2. Add each claimed country to the map
  3. Country already claimed?
    YesFail startup: name both providersNoContinue
  4. Every required country covered?
    YesMake the map immutable, readyNoFail startup: list missing countries

4 steps in order. Play them, or step through them one at a time.

Configuration mistakes stop the deployment instead of a payment.

5Adding a Provider Without Touching the Router

To launch in Poland with a new provider, a team writes one class and nothing else.

Java
@Component
class Przelewy24Provider implements PaymentProvider {
public Set<CountryCode> supportedCountries() { return Set.of(CountryCode.PL); }
public PaymentResult pay(Payment p) { /* call the provider */ }
}
// Next startup: byCountry gains PL=Przelewy24Provider; PaymentRouter unchanged

This is the open-closed principle in practice: the router is open to new providers and closed to modification. A provider can also be switched per environment with @ConditionalOnProperty or a profile, so a sandbox provider can claim all countries in a test environment.

6Testing the Router

Because the router is a plain class with a constructor, its tests need no Spring context. We pass fake providers and assert the routing and the failures.

Java
@Test void rejectsDuplicateCountry() {
var a = fake("A", CountryCode.DE); var b = fake("B", CountryCode.DE);
assertThatThrownBy(() -> new PaymentRouter(List.of(a, b), props(Set.of())))
.hasMessageContaining("DE is claimed by both"); // passes
}
@Test void routesByCountry() {
var router = new PaymentRouter(List.of(fake("A", CountryCode.DE), fake("B", CountryCode.US)), props(Set.of()));
assertThat(router.pay(payment(CountryCode.US)).provider()).isEqualTo("B"); // passes
}

One integration test that starts the real context is also worth having, because it proves the real set of provider beans and the production configuration pass the startup checks.

7Follow-up questions

Why not inject Map<String, PaymentProvider> and use the country as the bean name?

Bean names are a poor place for business data. A provider usually serves several countries, the names would have to be renamed when a country moves, and a typo in a name would simply create an unmapped country. Letting each provider declare its countries keeps the rule in one visible, testable place.

How would you handle a provider outage?

With an ordered list of providers per country, the router can try the next one when the first fails with a retryable error or when a circuit breaker for that provider is open. The fallback order should come from configuration so that operations can change it during an incident without a deployment.

Does the order of the injected list matter here?

Not for correctness, because duplicates are rejected and each country maps to one provider. If we allow backups, order matters, and we should set it explicitly with @Order or a configured priority, not rely on bean registration order.

8Conclusion

In this answer, we replaced a growing if-else block with a router built on collection injection. Each PaymentProvider declares the countries it supports, the router injects List<PaymentProvider> and builds an immutable country map in its constructor, and startup fails fast when two providers claim the same country or a required country has no provider. Routing becomes a single map lookup, new providers are added as beans without touching the router, and the design is easy to test with plain fakes.

What to say in the interviewAbout 90 seconds aloud

Open with

I would move the knowledge of which provider serves which country into the providers themselves. The PaymentProvider interface gets a method like supportedCountries, returning a set of a CountryCode value type, or the countries come from configuration per provider.

Then, if they want more

Each provider is an ordinary bean. The router injects List of PaymentProvider, which gives me every provider bean, and in its constructor builds an EnumMap from country to provider, then wraps it as unmodifiable so it is safe to read from many threads. Two checks run while building it, and they are the most important part.

If two providers claim the same country, startup fails with a message naming both, instead of one silently winning. And if a required country from configuration has no provider, startup fails too. So mistakes stop the deployment, not a customer's payment.

At runtime, pay is just a map lookup and a delegate call, constant time, and the router never mentions a provider class. Adding Poland means writing one new provider bean that claims PL, and the router is unchanged, which is the open-closed principle in practice.

If we later need backups, each country maps to an ordered list with explicit priorities, and the router falls back when a provider is down. The router is plain Java, so I unit test it with fake providers, plus one context test that proves the real configuration passes the startup checks.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Design a payment router that selects one of several PaymentProvider beans by country at...": https://scrivio-interview-library.netlify.app/spring-boot/dependency-injection/8e7bab0c55/