Swiftorial Logo
Home
Swift Lessons
AI Tools
Learn More
Career
Resources

Spring Framework FAQ: Top Questions

39. What are conditional beans in Spring?

Conditional beans are beans that are registered in the Spring context only when certain conditions are met, using the @Conditional annotation.

📘 Usage:

  • Apply @Conditional to classes or methods that create beans.
  • Define conditions by implementing Condition interface.

📥 Example:

@Bean
@Conditional(OnProdEnvironment.class)
public DataSource prodDataSource() {
  return new HikariDataSource();
}

🏆 Expected Output:

Bean is registered only if OnProdEnvironment condition returns true.

🛠️ Use Cases:

  • Environment-specific configurations.
  • Loading beans conditionally based on system properties or profiles.