最常被使用的 **ApplicationContext** 接口实现:
**FileSystemXmlApplicationContext**:该容器从 XML 文件中加载已被定义的 bean。在这里,你需要提供给构造器 XML 文件的完整路径。**ClassPathXmlApplicationContext**:该容器从 XML 文件中加载已被定义的 bean。在这里,你不需要提供 XML 文件的完整路径,只需正确配置 CLASSPATH 环境变量即可,因为,容器会从 CLASSPATH 中搜索 bean 配置文件。**WebXmlApplicationContext**:该容器会在一个 web 应用程序的范围内加载在 XML 文件中已被定义的 bean。
使用 `FileSystemXmlApplicationContext` 获取 **bean** 对象
- 先生成工厂对象。加载完指定路径下
**bean**配置文件后,利用框架提供的`FileSystemXmlApplicationContext`API 去生成工厂**bean**。**FileSystemXmlApplicationContext**负责生成和初始化所有的对象,比如,所有在 XML bean 配置文件中的**bean**。 - 利用上面生成的上下文中的
**getBean()**方法得到所需要的**bean**。 这个方法通过配置文件中的 bean ID 来返回一个真正的对象。一旦得到这个对象,就可以利用这个对象来调用任何方法。
案例代码:
Person.java
package com.baklib.custom;public class Person {private String name;private String carType;public String getName() {return name;}public void setName(String name) {this.name = name;}public String getCarType() {return carType;}public void setCarType(String carType) {this.carType = carType;}public void buyCar(){System.out.println(this.getName()+"购买了"+this.getCarType()+"!");}}
MainAPP.java
package com.baklib.custom;import org.springframework.context.ApplicationContext;import org.springframework.context.support.FileSystemXmlApplicationContext;public class MainApp {public static void main(String[] args) {// 绝对路径获取 Bean 配置文件ApplicationContext context = new FileSystemXmlApplicationContext("C:/project/Java/Spring/SpringPractice/src/main/resources/Beans.xml");// 相对路径获取 Bean 配置文件// ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml");Person person = (Person) context.getBean("person");person.setCarType("小轿车");person.buyCar();}}
配置文件 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="person" class="com.baklib.custom.Person"><property name="name" value="张三" /><property name="carType" value="" /></bean></beans>
编写完以上代码,就可以运行这个程序,运行结束后,可以在控制台看到下面的信息
张三购买了小轿车!
