Spring Boot – @ConditionalOnProperty

 


🌱 Spring Boot – @ConditionalOnProperty

1️⃣ What is @ConditionalOnProperty?

@ConditionalOnProperty is a Spring Boot conditional annotation that controls whether a bean should be created or not, based on the value of a property defined in application.properties or application.yml.

👉 In simple words:
Bean creation depends on configuration values.


2️⃣ Why do we need Conditional Bean Creation?

In real-world applications:

  • Different environments need different configurations
  • Some features must be enabled/disabled dynamically
  • We may want only one implementation active at a time

Spring Boot solves this using conditional annotations, and one of the most commonly used is @ConditionalOnProperty.


3️⃣ Problem Without @ConditionalOnProperty

❌ Default Behavior

If multiple beans exist:

  • Spring creates all beans
  • May lead to:
    • Unnecessary initialization
    • Conflicts
    • Higher memory usage
    • Startup errors

4️⃣ Use Cases (From Your PDF)

✅ Use Case 1

👉 Create only ONE bean
Either:

  • MySQLConnection
  • OR NoSQLConnection

Not both at the same time.


✅ Use Case 2

👉 Same codebase, different components need different DBs

  • Component A → MySQL
  • Component B → NoSQL

5️⃣ Solution: @ConditionalOnProperty

Spring Boot provides:

@ConditionalOnProperty(
    name = "db.type",
    havingValue = "mysql",
    matchIfMissing = false
)

This tells Spring:

  • Create this bean only if property matches
  • Otherwise → skip bean creation

6️⃣ Example Implementation

🔹 MySQL Bean

@Component
@ConditionalOnProperty(
    name = "database",
    havingValue = "mysql"
)
public class MySQLConnection {

    public MySQLConnection() {
        System.out.println("Initialization of MySQLConnection Bean");
    }
}

🔹 NoSQL Bean

@Component
@ConditionalOnProperty(
    name = "database",
    havingValue = "nosql"
)
public class NoSQLConnection {

    public NoSQLConnection() {
        System.out.println("Initialization of NoSQLConnection Bean");
    }
}

🔹 application.properties

database=mysql

✔ Result:

  • Only MySQLConnection bean is created
  • NoSQLConnection is ignored

7️⃣ Important Attributes of @ConditionalOnProperty

Attribute Meaning
name Property key
havingValue Required value to enable bean
matchIfMissing Create bean if property is absent

Example:

@ConditionalOnProperty(
    name = "feature.logging",
    havingValue = "true",
    matchIfMissing = true
)

8️⃣ Real-World Examples (Extra Points)

✅ Enable/Disable:

  • Payment gateways (Razorpay / Paytm)
  • Cache (Redis ON/OFF)
  • Messaging (Kafka / RabbitMQ)
  • Feature flags

✅ Environment based:

  • Dev → H2 DB
  • Prod → MySQL / Oracle

9️⃣ Advantages (From PDF + Added)

✔ Feature toggling
✔ Avoid unnecessary beans
✔ Reduce memory usage
✔ Faster application startup
✔ Clean environment-based configuration


🔟 Disadvantages (From PDF + Added)

❌ Misconfiguration can break app
❌ Hard to debug if properties are wrong
❌ Overuse increases code complexity
❌ Multiple similar beans cause confusion
❌ Difficult to manage in very large projects


1️⃣1️⃣ Best Practices (Added)

✅ Use clear property names
✅ Document properties properly
✅ Avoid overusing conditional beans
✅ Prefer profiles (@Profile) when suitable
✅ Log active configurations at startup


🧠 Interview Questions & Answers

Q1️⃣ What is @ConditionalOnProperty?

Answer:
It is a Spring Boot annotation used to create beans conditionally based on application property values.


Q2️⃣ Why do we need @ConditionalOnProperty?

Answer:
To control bean creation dynamically, avoid unnecessary beans, and support environment-based configurations.


Q3️⃣ Difference between @Profile and @ConditionalOnProperty?

Answer:

  • @Profile → Environment based
  • @ConditionalOnProperty → Property value based (more flexible)

Q4️⃣ What happens if property value does not match?

Answer:
The bean is not created and skipped during application startup.


Q5️⃣ What is matchIfMissing = true?

Answer:
If the property is missing, the bean will still be created.


Q6️⃣ Can multiple beans use the same property?

Answer:
Yes, but different havingValue must be used to avoid conflicts.


Q7️⃣ Is @ConditionalOnProperty evaluated at runtime?

Answer:
No, it is evaluated during application startup.


Q8️⃣ Common mistake with @ConditionalOnProperty?

Answer:
Wrong property key or value in application.properties.


📌 Summary (One-Line)

@ConditionalOnProperty helps build flexible, configurable, and environment-aware Spring Boot applications.

 

Leave a Reply