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

时间:2016-06-18 19:59:23

标签: spring annotations spring-java-config

--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?

1 个答案:

答案 0 :(得分:2)

@ComponentScan允许spring通过@Component注释自动扫描所有组件。 Spring使用base-package属性,该属性指示在何处查找组件。

@Configuration使用@Component进行元注释,这表示它符合类路径扫描的条件。

使用

时,

@Configuration(AppConfig类)已注册

AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);

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