Skip to content

Instantly share code, notes, and snippets.

View dstoianov's full-sized avatar
🏠
Working from home

Denys Stoianov dstoianov

🏠
Working from home
  • Berlin, Germany
  • 19:43 (UTC +01:00)
View GitHub Profile
@Toparvion
Toparvion / HOWTO.md
Last active November 17, 2024 05:56
JUnit test for conditional Spring Boot bean registration (@ConditionalOnProperty)

Problem

Suppose you have two classes that should be registered with Spring context exclusively, e.g. only one of the beans must exist in the context at any time based on some boolean property value. Of course you can do it by adding explicit if condition into your @Configuration class. But if the classes have no common interface it may be quite cumbersome. As an alternative you can use @ConditionalOnProperty annotation on your classes, e.g.:

@Service
@ConditionalOnProperty(name = "use-left-service", havingValue = "true", matchIfMissing = false)
public class LeftService