Spring 1.2.3. Using the container 容器的使用
The ApplicationContext is the interface for an advanced factory capable of maintaining a registry of different beans and their dependencies. Using the method T getBean(String name, Class<T> requiredType)
you can retrieve instances of your beans.
ApplicationContext是一个高级工厂的接口,能够维持不同bean以及他们依赖项的注册表。使用T getBean(String name, Class<T> requiredType)
你可以获得你想要的bean的实例
The ApplicationContext enables you to read bean definitions and access them as follows:
你可以通过如下的方式来读取bean的定义并访问他们
// create and configure beans
ApplicationContext context = new ClassPathXmlApplicationContext("services.xml", "daos.xml");
// retrieve configured instance
PetStoreService service = context.getBean("petStore", PetStoreService.class);
// use configured instance
List<String> userList = service.getUsernameList();
With Groovy configuration, bootstrapping looks very similar, just a different context implementation class which is Groovy-aware (but also understands XML bean definitions):
对于Groovy方式的配置,引导程序看起来很相像,唯一不同的是换了一个ApplicationContext的实现类
ApplicationContext context = new GenericGroovyApplicationContext("services.groovy", "daos.groovy");
The most flexible variant is GenericApplicationContext in combination with reader delegates, e.g. with XmlBeanDefinitionReader for XML files:
最灵活的变种是使用GenericApplicationContext 结合不同的reader读者代表,以下是基于xml的形式
GenericApplicationContext context = new GenericApplicationContext();
new XmlBeanDefinitionReader(context).loadBeanDefinitions("services.xml", "daos.xml");
context.refresh();
以下是Groovy的形式
GenericApplicationContext context = new GenericApplicationContext();
new GroovyBeanDefinitionReader(context).loadBeanDefinitions("services.groovy", "daos.groovy");
context.refresh();
Such reader delegates can be mixed and matched on the same ApplicationContext, reading bean definitions from diverse configuration sources, if desired.
这样的reader代笔可以在相同的ApplicationContext上混合和匹配,如果需要读取不同bean配置源的话
You can then use getBean
to retrieve instances of your beans. The ApplicationContext interface has a few other methods for retrieving beans, but ideally your application code should never use them. Indeed, your application code should have no calls to the getBean() method at all, and thus no dependency on Spring APIs at all. For example, Spring’s integration with web frameworks provides dependency injection for various web framework components such as controllers and JSF-managed beans, allowing you to declare a dependency on a specific bean through metadata (e.g. an autowiring annotation).
你可以使用getBean方法获取并实例化你的bean,ApplicationContext接口还提供了集中不同的方式来获取bean.但是,理想情况下,你的应用程序代码中应该永远不要使用它们。事实上,你的应用程序就不应该有对getBean()
方法的调用,也不应该对spring 的 api产生任何依赖。例如,spring和web框架的整合为各种web框架的组件提供了依赖注入,例如controllers,基于javawe标准框架的JSF-managed 的beans,允许你通过元数据的形式来声明对特定bean的依赖关系