7.2.3 使用容器

ApplicationContext是一个高级工厂的接口,这个工厂能够维护不同的bean及其依赖的注册表。使用T getBean(String name, Class<T> requiredType)方法可以取回bean的实例。

通过ApplicationContext可以读取bean定义并访问bean,如下所示:

  1. // create and configure beans
  2. ApplicationContext context = new ClassPathXmlApplicationContext("services.xml", "daos.xml");
  3. // retrieve configured instance
  4. PetStoreService service = context.getBean("petStore", PetStoreService.class);
  5. // use configured instance
  6. List<String> userList = service.getUsernameList();

使用Groovy配置,引导程序(bootstrapping)看起来非常相似,只不过是一个能识别Groovy(但也能理解XML的bean定义)的不同的上下文实现类:

  1. ApplicationContext context = new GenericGroovyApplicationContext("services.groovy", "daos.groovy");

最灵活的用法是组合GenericApplicationContext与reader代理,例如使用针对XML文件的XmlBeanDefinitionReader

  1. GenericApplicationContext context = new GenericApplicationContext();
  2. new XmlBeanDefinitionReader(context).loadBeanDefinitions("services.xml", "daos.xml");
  3. context.refresh();

或者使用针对Groovy文件的GroovyBeanDefinitionReader

  1. GenericApplicationContext context = new GenericApplicationContext();
  2. new GroovyBeanDefinitionReader(context).loadBeanDefinitions("services.groovy", "daos.groovy");
  3. context.refresh();

这样的reader代理可以在同一个ApplicationContext上混合和匹配,如果需要,可以从不同的配置源读取bean定义。

然后可以使用getBean取回bean的实例。ApplicationContext接口中还有一些其他的方法来获取bean,但理想状态下程序中应该用不到它们。事实上,您的应用程序代码根本就不应该调用getBean()方法,因此完全不依赖于Spring的API。例如,Spring与Web框架的集成为各种Web框架组件(如控制器和JSF管理的bean)提供了依赖注入,允许您通过元数据(比如一个自动绑定注解)声明对特定bean的依赖。