Suppose that you have a webshop with a credit card payment option. Credit card payments work fine in a production environment. There is a new requirement to implement a sandbox environment for the webshop. Sandbox environment doesn’t charge your credit card. It always returns a successful response.
Each checkout implementation is based on the following CheckoutService interface:
However, we want to instantiate either BankCheckoutService or SandboxCheckoutService based on the variable in the application properties file. SandboxCheckoutService should be instantiated if application properties contains the following content:
If sandbox the variable is false BankCheckoutService will be instantiated.
Spring Boot already has a solution. @ConditionalOnProperty annotation provides us the possibility to conditionally instantiate bean based on property value from application.properties file.
The controller doesn’t have to be changed since it expects CheckoutService interface which is implemented in both BankCheckoutService and SandboxCheckoutService. Controller depends on abstraction not implementation as it is specified in SOLID principle.
We can now switch between BankCheckoutService and SandboxCheckoutService by changing the sandbox variable in the application.properties file.