spring 框架说明文档学习记录(3)

来源:互联网 发布:淘宝买装饰画 编辑:程序博客网 时间:2024/05/22 19:44

三、IOC容器

    org.springframework.beans和org.springframework.context是spring框架的IOC容器的基础。其中BeanFactory提供配置框架和基础功能,ApplicationContext是BeanFactory的子接口,添加了更多企业专用的功能。

    接口org.springframework.context.ApplicationContext代表Spring IOC容器并负责初始化、配置、聚集各种bean。容器通过读取配置元数据来获取如何初始化、配置和聚集对象。配置元数据通过XML、java 注解或java代码来体现。它允许你描述组成你应用的对象和对象间的依赖关系。

 

    初始化容器

    初始化一个spring IOC容器很简单

    ApplicationContextcontext = new ClassPathXmlApplicationContext(new String[]{"services.xml", "daos.xml"});

    构造函数中的参数,实际上是一些资源字符串,通过这些字符串,容器能够从本地系统的各种外部资源、从java的CLASSPATH等各种路径获取配置元数据。


    services.xml示例

<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans.xsd"><!-- services --><bean id="petStore" class="org.springframework.samples.jpetstore.services.PetStoreServiceImpl"><property name="accountDao" ref="accountDao"/><property name="itemDao" ref="itemDao"/><!-- additional collaborators and configuration for this bean go here --></bean><!-- more bean definitions for services go here --></beans>


    组合基于xml的元数据

<beans><import resource="services.xml"/><import resource="resources/messageSource.xml"/><import resource="/resources/themeSource.xml"/><bean id="bean1" class="..."/><bean id="bean2" class="..."/></beans>

使用容器

ApplicationContext是你能够读取bean定义并使用他们

// create and configure beansApplicationContext context =new ClassPathXmlApplicationContext(new String[] {"services.xml", "daos.xml"});// retrieve configured instancePetStoreService service = context.getBean("petStore", PetStoreService.class);// use configured instanceList<String> userList = service.getUsernameList();







0 0