Conditional Dependency Injection In Spring Framework And Spring Boot

İbrahim Gündüz
2 min readFeb 6, 2025

--

Problem:

To test the application code with minimal mocking effort, we want to make the payment processor implementation configurable so that the application can use the dummy processor if none is configured.

Solutions:

1- Factory Method In The Configuration Class

With this solution, you can create beans conditionally by a factory method created in the configuration class. You can create an instance of the desired implementation based on a system property and an instance of fallback implementation otherwise. It doesn’t create extra beans.

Let’s test it and see how it works.

2. Conditional Annotation

The @Conditional annotation allows the registration of beans based on custom conditions. It can be defined at the class or method level. You can define the logic that determines whether the bean should be created by creating a class that implements org.springframework.context.annotation.Condition interface.

To implement this solution, let’s create our condition classes like the ones below:

Add @Conditional annotation to the implementation classes and pass the appropriate condition classes as arguments.

Finally, run the following test to see how it works.

3. ConditionalOnProperty Annotation

This annotation registers the bean only if the specified property is present in the application config and, optionally has a specified value. This annotation is available only in Spring Boot.

You can run the same test code from the previous example.

3. @Profile Annotation

Profile annotation allows the registration of beans based on the active application profile.

You can test the code above, just by changing the active profile in the test code as below

Thanks for reading! You can find all the examples in the following repository.

Credits

--

--

No responses yet