Thursday, 3 July 2025

Why we use @Configuration, @EnableAutoConfiguration in Spring Boot (and Spring Framework)

1) @Configuration

In Spring Boot (and Spring Framework), we use the @Configuration annotation to indicate that a Java class contains Spring bean definitions — essentially replacing the older applicationContext.xml style configuration.


✅ What is @Configuration?

@Configuration is an annotation provided by Spring that marks a class as a source of bean definitions. It is part of Java-based configuration introduced in Spring 3.

java
@Configuration public class AppConfig { @Bean public MyService myService() { return new MyServiceImpl(); } }

✅ Why We Use @Configuration in Spring Boot

PurposeDescription
1. Java-based configurationAllows you to define beans using Java code instead of XML.
2. Enables @Bean methodsMethods annotated with @Bean inside a @Configuration class are registered as beans in the Spring context.
3. Singleton behaviorSpring ensures that each @Bean method returns a singleton bean by default — even if the method is called multiple times.
4. Component scanningIt works with @ComponentScan and @EnableAutoConfiguration (often combined in @SpringBootApplication).
5. ModularityHelps you modularize configuration by splitting it into multiple @Configuration classes.

✅ Example
java
@Configuration public class AppConfig { @Bean public UserService userService() { return new UserServiceImpl(); } @Bean public UserRepository userRepository() { return new UserRepositoryImpl(); } }

🔁 Compared with @Component

  • @Component tells Spring "this is a bean".

  • @Configuration tells Spring "this class defines multiple beans", and provides enhanced control over bean creation using @Bean.


✅ Behind the scenes

@Configuration is internally a specialized @Component, so Spring can automatically detect it via component scanning.

java
@Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Documented @Component public @interface Configuration { boolean proxyBeanMethods() default true; }

🧠 Bonus Tip: proxyBeanMethods = false (Spring 5.2+)

java
@Configuration(proxyBeanMethods = false) public class AppConfig { // ... }
  • Use this if you don't need Spring to proxy @Bean methods.

  • Improves performance, but disables method call interception between beans in the same config class.


✅ Summary

Feature@Configuration
ReplacesXML config (applicationContext.xml)
SupportsDefining beans using @Bean methods
Registered asA Spring-managed component
EnsuresSingleton beans, method call safety
Used with@ComponentScan, @SpringBootApplication, etc.

2) @EnableAutoConfiguration

In Spring Boot, we use @EnableAutoConfiguration to automatically configure Spring application context based on the classpath contents, defined beans, and configuration properties — removing the need for most manual bean declarations.


✅ What is @EnableAutoConfiguration?

@EnableAutoConfiguration tells Spring Boot:

"Try to automatically configure beans and settings based on what’s available on the classpath and what the developer has configured."


✅ Why We Use @EnableAutoConfiguration

PurposeDescription
✅ Auto configurationAutomatically configures beans for components like DataSource, JPA, Kafka, RabbitMQ, Redis, Web, etc., if relevant classes are on the classpath.
✅ Eliminates boilerplateRemoves the need for manual configuration (e.g., no need to define DataSource bean for Spring JDBC).
✅ Conditional configurationUses @ConditionalOnClass, @ConditionalOnMissingBean, etc., to apply configuration only when needed.
✅ Part of @SpringBootApplicationIt is implicitly included in @SpringBootApplication, so most of the time you don’t need to add it manually.

✅ Example

java
@SpringBootApplication // Includes @EnableAutoConfiguration public class MyApp { public static void main(String[] args) { SpringApplication.run(MyApp.class, args); } }

Equivalent breakdown:

java
@Configuration @ComponentScan @EnableAutoConfiguration public class MyApp { ... }

✅ Real-world Usage Example

If you include spring-boot-starter-web, Spring Boot sees:

  • DispatcherServlet on the classpath

  • So it auto-configures:

    • A DispatcherServlet bean

    • A RequestMappingHandlerMapping

    • JSON converters

    • Embedded Tomcat server

If you include spring-boot-starter-data-jpa, it auto-configures:

  • DataSource

  • EntityManagerFactory

  • TransactionManager

Without writing any XML or Java configuration.


✅ How It Works Internally

  • It loads configuration classes from:

txt
META-INF/spring.factories

Which looks like this:

properties
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration,\ org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration,\ ...
  • These classes are conditionally applied using @ConditionalOnClass, @ConditionalOnMissingBean, etc.


✅ Disable Specific Auto Configs

If you don’t want Spring Boot to auto-configure something:

java
@EnableAutoConfiguration(exclude = {DataSourceAutoConfiguration.class})

✅ Summary

FeatureDescription
PurposeAutomatically configures Spring beans based on classpath, properties, and environment
Included in@SpringBootApplication
ReplacesManual bean definitions
Controlled byConditions (e.g., class presence, bean presence)
Config loaded fromspring.factories under META-INF
Can be disabledYes, via exclude or spring.autoconfigure.exclude

No comments:

Post a Comment