IoC容器总览

Spring围绕着IoC为中心,通过容器管理程序的组件。

org.springframework.context.ApplicationContext接口代表IoC容器,负责实例化、组装和设置bean。

单独的应用常常创建ClassPathXmlApplicationContextFileSystemXmlApplicationContext实例。

容器通过读取配置元数据获得指令来实例化、组装和设置对象。

配置元数据(metadata)通过xml文件、Java注解或Java代码表示。

Spring IoC容器

现在多用Java代码来配置元数据。

xml配置元数据文件:

在顶层的<beans/>元素里面添加<bean/>元素:

<?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/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="..." class="...">  
        <!-- 在这里修饰或者设置bean -->
    </bean>

    <bean id="..." class="...">
        <!-- 在这里修饰或者设置bean -->
    </bean>

    <!-- 在这里添加更多bean定义 -->

</beans>

上面的id属性用来区分单独的bean定义。

class属性定义了bean的类型,为类名的全称。

如何实例化:

ApplicationContext context = new ClassPathXmlApplicationContext("services.xml", "daos.xml");

组合多个xml文件:

<beans/>元素有个<import/>元素可以载入别的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接口的T getBean(String name, Class<T> requiredType)方法:

ApplicationContext context = new ClassPathXmlApplicationContext("services.xml", "daos.xml");
PetStoreService service = context.getBean("petStore", PetStoreService.class);
List<String> userList = service.getUsernameList();

留下评论

您的电子邮箱地址不会被公开。 必填项已用 * 标注