Spring Conditional Bean Configuration: Load Beans Based on Application Properties File

In complex applications, there are times when you will want the Spring dependency injector to create an instance of a class based on a given condition. One common case is to configure the bean definition based on a property defined in the application.properties file. By using this approach you can load custom beans at runtime without recompiling your entire application. This is where the Spring conditional bean configuration mechanisms come in handy.

As an example, we can create a VAT (value added tax) calculator. Various countries have various rates for this tax.

Let’s externalize the country in the application.properties file and load a specific VAT calculator bean based on the value of this property. The property name will be ‘country’.

# available options: croatia/romania
country=croatia

Now we can create the VatCalculator interface and the specific implementations. Since we can not load both components at the same time, then we need to let Spring know that we want to load a specific bean based on the value of the ‘country’ property. This can be achieved quite easily by using the @ConditionalOnProperty annotation, like in the example below.

public interface VatCalculator {
  double calculateVat(int price);
}

@Component
@ConditionalOnProperty(name = "country", havingValue = "croatia")
public class CroatiaVatCalculator implements VatCalculator {
  @Override
  public double calculateVat(int price) {
    return 0.25 * price;
  }
}

@Component
@ConditionalOnProperty(name = "country", havingValue = "romania")
public class RomanianVatCalculator implements VatCalculator {
  @Override
  public double calculateVat(int price) {
    return 0.19 * price;
  }
}

The @ConditionalOnProperty has two parameters:
name: used to specify the name of the property in the application.properties file
havingValue: used to specify the value the property needs to have for Spring to load this bean

You can learn more about how to use this annotation in the official Spring docs.

This is it. It only takes one line of code to implement a conditional bean definition in Spring using properties in the configuration file.