Search code examples
springannotationsspring-java-config

Can @Configuration work without @componentScan (Spring JavaConfig @annotaion)


--Appconfig.java

@Configuration
public class AppConfig {    

  @Bean(name="helloBean")
  public HelloWorld helloWorld() {
    return new HelloWorldImpl();
   }
}

--interface.java

public interface HelloWorld {
    void printHelloWorld(String msg);
} 

--ipml.java

public class HelloWorldImpl implements HelloWorld {
public void printHelloWorld(String msg) {
    System.out.println("Hello! : " + msg);
   --
}

--App.java

public class App {

public static void main(String[] args) {

    AnnotationConfigApplicationContext context = new 
    new AnnotationConfigApplicationContext(AppConfig.class);

HelloWorld obj = (HelloWorld) context.getBean(HelloWorldImpl.class);

obj.printHelloWorld("Spring3 Java Config");
   }
}

My program can works, but my question is why I don't need to add @componentScan in Appconfig.java .

It seems to @Configuration and @Bean can be found by Spring whithout using @componentScan.

I thought if you want to use @annotation ,you must use @componentScan or

context:component-scan(xml), am I right?


Solution

  • @ComponentScan allows spring to auto scan all your components with @Component annotated. Spring uses the base-package attribute, which indicates where to find components.

    @Configuration is meta annotated with @Component, which marks it eligible for classpath scanning.

    @Configuration (AppConfig class) is registered when you use

    AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
    

    @Bean doesn't need @ComponentScan as all these beans are created explicitly when spring encounters this annotation.