社区微信群开通啦,扫一扫抢先加入社区官方微信群
社区微信群
spring ApplicationContext容器
Application Context 是 BeanFactory 的子接口,也被成为 Spring 上下文。
Application Context 是 spring 中较高级的容器。和 BeanFactory 类似,它可以加载配置文件中定义的 bean,将所有的 bean 集中在一起,当有请求的时候分配 bean。ApplicationContext 包含 BeanFactory 所有的功能,一般情况下,相对于 BeanFactory,ApplicationContext 会更加优秀。当然,BeanFactory 仍可以在轻量级应用中使用,比如移动设备或者基于 applet 的应用程序。
最常被使用的 ApplicationContext 接口实现:
FileSystemXmlApplicationContext:该容器从 XML 文件中加载已被定义的 bean。在这里,你需要提供给构造器 XML 文件的完整路径。
ClassPathXmlApplicationContext:该容器从 XML 文件中加载已被定义的 bean。在这里,你不需要提供 XML 文件的完整路径,只需正确配置 CLASSPATH 环境变量即可,因为,容器会从 CLASSPATH 中搜索 bean 配置文件。
WebXmlApplicationContext:该容器会在一个 web 应用程序的范围内加载在 XML 文件中已被定义的 bean。
下面是我通过FileSystemXmlApplicationContext容器来获取bean的一个具体操作过程,和通过BeanFactory容器获取的操作类似:
下面是文件TestIoc02.java的内容
package org.TestIoc02;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
public class TestIoc02 {
public static void main(String[] args) {
ApplicationContext context = new FileSystemXmlApplicationContext
("D:\eclipse-workspace\IocTest\src\Beans.xml");
Tstudent student = (Tstudent)context.getBean("Tstudent02");
student.test();
}
}
下面是文件Tstudent.java的内容
package org.TestIoc02;
public class Tstudent {
private String IocInfo;
public void setIocInfo(String iocInfo) {
IocInfo = iocInfo;
}
public void test() {
System.out.println("this is ioc test! By using "+IocInfo);
}
}
下面是文件Beans.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/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="Tstudent02" class="org.TestIoc02.Tstudent">
<property name="iocInfo" value="ApplicationContext"></property>
</bean>
</beans>
下面是输出结果
如果觉得我的文章对您有用,请随意打赏。你的支持将鼓励我继续创作!