--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?
答案 0 :(得分:2)
@ComponentScan
允许spring通过@Component
注释自动扫描所有组件。 Spring使用base-package属性,该属性指示在何处查找组件。
@Configuration
使用@Component
进行元注释,这表示它符合类路径扫描的条件。
@Configuration
(AppConfig类)已注册
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
@Bean
不需要@ComponentScan
因为所有这些bean都是在春天遇到此注释时显式创建的。