使用 AnnotationConfigApplicationContext 实例化 Infra 容器
以下部分记录了 Infra 3.0 中引入的 Infra AnnotationConfigApplicationContext。
这个多功能的 ApplicationContext 实现不仅能够接受 @Configuration 类作为输入,还能够接受普通的 @Component 类和使用 JSR-330 元数据注解的类。
当提供 @Configuration 类作为输入时,@Configuration 类本身被注册为 bean 定义,并且类中所有声明的 @Bean 方法也被注册为 bean 定义。
当提供 @Component 和 JSR-330 类时,它们被注册为 bean 定义,并且假设在必要时在这些类中使用 DI 元数据,例如 @Autowired 或 @Inject。
简单构造
就像实例化 ClassPathXmlApplicationContext 时使用 Infra XML 文件作为输入一样,
您可以在实例化 AnnotationConfigApplicationContext 时使用 @Configuration 类作为输入。
这允许完全不使用 XML 的 Infra 容器使用,如下例所示:
-
Java
public static void main(String[] args) {
ApplicationContext ctx = new AnnotationConfigApplicationContext(AppConfig.class);
MyService myService = ctx.getBean(MyService.class);
myService.doStuff();
}
如前所述,AnnotationConfigApplicationContext 不仅限于只与 @Configuration 类一起工作。
任何 @Component 或 JSR-330 注解的类都可以作为输入提供给构造函数,如下例所示:
-
Java
public static void main(String[] args) {
ApplicationContext ctx = new AnnotationConfigApplicationContext(MyServiceImpl.class, Dependency1.class, Dependency2.class);
MyService myService = ctx.getBean(MyService.class);
myService.doStuff();
}
前面的示例假设 MyServiceImpl、Dependency1 和 Dependency2 使用 Infra 依赖注入注解,例如 @Autowired。
使用 register(Class<?>…) 以编程方式构建容器
您可以使用无参数构造函数实例化 AnnotationConfigApplicationContext,然后使用 register() 方法对其进行配置。
这种方法在以编程方式构建 AnnotationConfigApplicationContext 时特别有用。
以下示例显示了如何执行此操作:
-
Java
public static void main(String[] args) {
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
ctx.register(AppConfig.class, OtherConfig.class);
ctx.register(AdditionalConfig.class);
ctx.refresh();
MyService myService = ctx.getBean(MyService.class);
myService.doStuff();
}
使用 scan(String…) 启用组件扫描
要启用组件扫描,您可以按如下方式注解您的 @Configuration 类:
-
Java
@Configuration
@ComponentScan(basePackages = "com.acme") (1)
public class AppConfig {
// ...
}
| 1 | 此注解启用组件扫描。 |
|
经验丰富的 Infra 用户可能熟悉来自 Infra
|
在前面的示例中,扫描 com.acme 包以查找任何 @Component 注解的类,并将这些类注册为容器内的 Infra bean 定义。
AnnotationConfigApplicationContext 公开了 scan(String…) 方法以允许相同的组件扫描功能,如下例所示:
-
Java
public static void main(String[] args) {
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
ctx.scan("com.acme");
ctx.refresh();
MyService myService = ctx.getBean(MyService.class);
}
请记住,@Configuration 类是用 @Component 元注解 的,
因此它们是组件扫描的候选者。在前面的示例中,假设 AppConfig 声明在 com.acme 包(或其下的任何包)中,
它在调用 scan() 期间被拾取。在 refresh() 时,它的所有 @Bean 方法都会被处理并在容器内注册为 bean 定义。
|