org.springframework.beans.factory.BeanFactory 是最基本的 Spring 容器接口,它提供了管理 Bean 的一些基本功能。 BeanFactory 接口包含如下幾個基本方法: Object getBean(String name) throws BeansException; <T> T getBean(String name, Class<T> requiredType) throws BeansException; boolean containsBean(String name); Class<?> getType(String name) throws NoSuchBeanDefinitionException;
org.springframework.context.ApplicationContext 是org.springframework.beans.factory.BeanFactory 的子接口,除了提供BeanFactory 所支持的功能,ApplicationContext 還提供了一些額外的功能,如國際化支持、事件機制、資源訪問等。
Spring 配置文件的基本結構<?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 http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> <bean id="..." class="..." > <property name="..." value="..." /> <property name="..." ref="..." /> </bean> </beans>實例化容器
按文件系統路徑加載配置文件:
ApplicationContext appCtx = new FileSystemXmlApplicationContext("src/applicationContext.xml");按類路徑加載配置多件:
ApplicationContext appCtx = new ClassPathXmlApplicationContext("applicationContext.xml");加載多個配置文件:
ApplicationContext context = new ClassPathXmlApplicationContext(new String[] {"services.xml", "daos.xml"});使用 Spring 容器ExampleBean example = appCtx.getBean("example", ExampleBean.class);新聞熱點
疑難解答