Home > other >  What @EnableAutoConfiguration actually "auto-configured"?
What @EnableAutoConfiguration actually "auto-configured"?

Time:09-20

I'm reading Difference Between @ComponentScan and @EnableAutoConfiguration in Spring Boot article. See this:

It automatically creates and registers beans based on both the included jar files in the classpath and the beans defined by us.

When we define the spring-boot-starter-web dependency in our classpath, Spring boot auto-configures Tomcat and Spring MVC.

I can understand it creates and registers beans based on both the included jar files. But I can't figure out what exact things been configured. Does it mean it will execute some beans automatically? Or something else? Is there any other example explain this?

CodePudding user response:

@EnableAutoConfiguration turns on auto configuration. Auto configuration tries to locate spring beans that should be configured for your application based on dependencies find in your classpath. Spring search for META-INF/spring.factories files. When it is enabled auto configuration class pointed by the property is loaded.

Consider below code snippet from spring source code:

@AutoConfiguration(
after = {DataSourceAutoConfiguration.class}
) 
@ConditionalOnClass({DataSource.class, JdbcTemplate.class})
@ConditionalOnSingleCandidate(DataSource.class)
@EnableConfigurationProperties({JdbcProperties.class})
@Import({DatabaseInitializationDependencyConfigurer.class, 
         JdbcTemplateConfiguration.class, 
         NamedParameterJdbcTemplateConfiguration.class})
public class JdbcTemplateAutoConfiguration {
  public JdbcTemplateAutoConfiguration() {
  }
}

@ComponentScan on the other hand search for beans of your application code marked with stereotype annotations (@Component, @Controller, @Service, @Repository)

  • Related