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

mik*_*ang 2 spring annotations spring-java-config

--Appconfig.java

@Configuration
public class AppConfig {    

  @Bean(name="helloBean")
  public HelloWorld helloWorld() {
    return new HelloWorldImpl();
   }
}
Run Code Online (Sandbox Code Playgroud)

--interface.java

public interface HelloWorld {
    void printHelloWorld(String msg);
} 
Run Code Online (Sandbox Code Playgroud)

--ipml.java

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

--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");
   }
}
Run Code Online (Sandbox Code Playgroud)

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?

use*_*814 6

@ComponentScan允许 spring 自动扫描所有带有@Component注释的组件。Spring使用base-package属性,该属性指示在哪里可以找到组件。

@Configuration元注释为@Component,这标志着它符合类路径扫描的条件。

@Configuration(AppConfig类)在使用时注册

AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
Run Code Online (Sandbox Code Playgroud)

@Bean不需要@ComponentScan,因为所有这些 bean 都是在 spring 遇到此注释时显式创建的。