๐ฑ Spring Boot Interview Series – Auto-Configuration & Conditional Beans ๐
Spring Boot’s magic comes alive with Auto-Configuration and Conditional Beans! Let’s explore each concept in depth, with real-world examples, unknown facts, and colorful explanations. ๐
36. What is auto-configuration in Spring Boot? ๐ก
Auto-configuration in Spring Boot is the “magic wand” that automatically configures beans, settings, and features based on the classpath, existing beans, and properties, so you don’t have to write boilerplate code. ๐
@SpringBootApplication
public class MyApp {
public static void main(String[] args) {
SpringApplication.run(MyApp.class, args);
}
}
Unknown Fact: Auto-configuration happens after your own @Configuration
beans but before the application context is fully refreshed.
Common Mistake: Ignoring auto-config defaults may override your manual beans unintentionally!
37. How does Spring Boot discover auto-configuration classes? ๐
Spring Boot discovers auto-configuration classes by reading metadata files in the classpath, such as META-INF/spring.factories
(pre-3.x) or META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports
(3.x+), which list all auto-config classes the framework should consider. ๐งฉ
// Pseudo representation
SpringApplication.run() --> scans classpath --> reads META-INF/spring.factories --> registers auto-config beans
38. What is META-INF/spring.factories? ๐
META-INF/spring.factories
is a properties file inside Spring Boot starters or libraries that maps interfaces to implementation classes for auto-configuration, telling Spring Boot which classes to load automatically.
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration,\
org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration
Common Mistake: Modifying it incorrectly can break auto-configuration silently. ๐ฑ
39. How does Spring Boot auto-configuration change in Spring Boot 3.x? ๐
Spring Boot 3.x replaced spring.factories
with AutoConfiguration.imports
to speed up startup, reduce memory footprint, and avoid loading unnecessary classes. ⚡
Unknown Fact: This improves startup especially for large multi-module applications.
40. How to disable a specific auto-configuration? ❌
You can disable specific auto-configs either in annotations or properties:
@SpringBootApplication(exclude = DataSourceAutoConfiguration.class)
public class MyApp {}
spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration
Common Mistake: Excluding after the context is initialized will not work — it must be done at startup!
41. What is @EnableAutoConfiguration? ⚡
@EnableAutoConfiguration
tells Spring Boot to automatically configure beans based on the classpath and existing beans. It’s included in @SpringBootApplication
. Use it alone if you don’t want component scanning. ๐ค
42. How to write your own custom auto-configuration? ๐ ️
Steps to create a custom auto-config:
@Configuration
public class MyAutoConfig {
@Bean
public MyBean myBean() {
return new MyBean();
}
}
Then register in META-INF/spring.factories
(or .imports
in 3.x). Add conditional annotations to prevent conflicts.
43. What is @ConditionalOnClass? ๐งฉ
Bean is created only if a specific class exists on the classpath. Useful to avoid errors when optional dependencies are missing.
@Configuration
@ConditionalOnClass(name = "com.mysql.cj.jdbc.Driver")
public class MySqlAutoConfig {
@Bean
public DataSource dataSource() {
return new MysqlDataSource();
}
}
44. What is @ConditionalOnMissingBean? ❗
Bean is created only if no other bean of that type exists. This is how Spring Boot allows your custom beans to override default auto-config beans.
@Bean
@ConditionalOnMissingBean
public CacheManager cacheManager() {
return new SimpleCacheManager();
}
45. What is @ConditionalOnProperty? ๐
Bean is created only if a specific property exists or matches a value. Perfect for feature toggles.
@Configuration
@ConditionalOnProperty(name = "featureX.enabled", havingValue = "true")
public class FeatureXConfig {}
46. What is @ConditionalOnMissingClass? ๐ซ
Bean is created only if a certain class is NOT present. Opposite of @ConditionalOnClass
. Helps provide defaults when optional libraries are absent.
@Configuration
@ConditionalOnMissingClass("com.mongodb.MongoClient")
public class DefaultStorageConfig {}
47. How to use @Conditional with custom conditions? ๐ ️
For complex logic, implement Condition
interface:
public class MyCondition implements Condition {
@Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
return Boolean.parseBoolean(context.getEnvironment().getProperty("my.feature.enabled", "false"));
}
}
@Configuration
@Conditional(MyCondition.class)
public class MyConditionalConfig {}
Unknown Fact: Custom conditions can control bean creation dynamically based on environment, classpath, or even external services! ๐
Wrapping Up ๐
Auto-Configuration and Conditional Beans are the heart of Spring Boot’s “magic” — they save you boilerplate, give you flexibility, and let your apps adapt dynamically. But remember: misunderstanding conditions or exclusions can silently break your app, so always test carefully. Try writing a custom auto-config once — you’ll feel like a Spring wizard! ๐ง♂️✨
Comments
Post a Comment