Spring框架中的@Import注解向我们展示了@Import的两种用法:
此处,ParentConfig是主配置,JavaConfigA和JavaConfigB都是@Configuration类,各自用@Bean方法定义了自己的Bean。
在4.2以后,也可以导入普通的java类,并将其声明成一个bean
// 一个普通java类
public class DemoService {
public void doSomething(){
System.out.println("ok");
}
}
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
// Configuration将导入DemoService
@Configuration
@Import(DemoService.class) //在spring 4.2之前是不不支持的
public class DemoConfig {
}
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class Main {
public static void main(String[] args) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext("com..example");
DemoService ds = context.getBean(DemoService.class);
ds.doSomething();
}
}
输出结果:ok
阅读Spring - @Configuration selection by using ImportSelector中的Using Annotation based ImportSelector部分