Spring Boot - @EnableAutoConfiguration with @ComponentScan

[Updated: Dec 6, 2016, Created: Dec 5, 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 Web Starter 1.4.2.RELEASE: Starter for building web, including RESTful, applications using Spring MVC. Uses Tomcat as the default embedded container.
    Corresponding Spring version: 4.3.4.RELEASE
  • JDK 1.8
  • Maven 3.3.9

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

See Also