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
  • 12:29 (UTC +02:00)
View GitHub Profile
@Toparvion
Toparvion / HOWTO.md
Last active May 23, 2024 02:35
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