java 39 lines · 6 steps

Swapping payment gateways by profile in Spring

One config class defines three PaymentGateway beans, and the active Spring profile picks exactly which one loads.

Explained by highlit
1package com.example.payments.config;
2 
3import com.stripe.StripeClient;
4import org.springframework.beans.factory.annotation.Value;
5import org.springframework.context.annotation.Bean;
6import org.springframework.context.annotation.Configuration;
7import org.springframework.context.annotation.Profile;
8 
9@Configuration
10public class PaymentGatewayConfig {
11 
12 @Bean
13 @Profile("local")
14 public PaymentGateway sandboxPaymentGateway() {
15 return new StubPaymentGateway();
16 }
17 
18 @Bean
19 @Profile("staging")
20 public PaymentGateway stagingPaymentGateway(
21 @Value("${stripe.test-key}") String testKey) {
22 StripeClient client = StripeClient.builder()
23 .setApiKey(testKey)
24 .build();
25 return new StripePaymentGateway(client, false);
26 }
27 
28 @Bean
29 @Profile("production")
30 public PaymentGateway livePaymentGateway(
31 @Value("${stripe.live-key}") String liveKey,
32 @Value("${stripe.webhook-secret}") String webhookSecret) {
33 StripeClient client = StripeClient.builder()
34 .setApiKey(liveKey)
35 .setConnectTimeout(5_000)
36 .build();
37 return new StripePaymentGateway(client, true, webhookSecret);
38 }
39}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Binding beans to profiles lets one interface resolve to different implementations per environment without conditional code.
  2. 2Injecting secrets through @Value keeps keys out of source and scoped to the environment that needs them.
  3. 3A stub implementation for local development removes any dependency on live external services.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Swapping payment gateways by profile in Spring — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code