Close

Spring Boot - @EnableAutoConfiguration with @ComponentScan

[Last Updated: Dec 6, 2016]

In a boot application, Spring core component scanning doesn't work by just using @EnableAutoConfiguration. We have to additionally use @ComponentScan:


Example using @ComponentScan with @EnableAutoConfiguration

<project ...>
  ....
 <parent>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-parent</artifactId>
  <version>1.4.2.RELEASE</version>
 </parent>
   ....
 <dependencies>
  <dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-web</artifactId>
  </dependency>
 </dependencies>
</project>
@Component
public class MyBean {
   public String getMessage () {
       return "a message from MyBean";
   }
}
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class MyWebController {

   @Autowired
   private MyBean myBean;

   @RequestMapping("/")
   @ResponseBody
   public String theHandler () {
       return myBean.getMessage();
   }
}

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.Bean;

@ComponentScan
@EnableAutoConfiguration
public class EnabledAutoConfigExample {

   public static void main (String[] args) {
       SpringApplication.run(EnabledAutoConfigExample.class, args);
   }
}

Note that if no packages are defined by using ComponentScan(basePackages) or ComponentScan(basePackageClasses), the scanning will happen from the package of the class that declares this annotation.

Output in browser






Example Project

Dependencies and Technologies Used:

  • Spring Boot 1.4.2.RELEASE
    Corresponding Spring Version 4.3.4.RELEASE
  • Spring Boot Web Starter : Starter for building web, including RESTful, applications using Spring MVC. Uses Tomcat as the default embedded container.
  • JDK 1.8
  • Maven 3.3.9

Spring Config Scanning Select All Download
  • spring-boot-scanning
    • src
      • main
        • java
          • com
            • logicbig
              • example
                • EnabledAutoConfigScanExample.java

    See Also