最常被使用的 **ApplicationContext** 接口实现:

    • **FileSystemXmlApplicationContext**:该容器从 XML 文件中加载已被定义的 bean。在这里,你需要提供给构造器 XML 文件的完整路径。
    • **ClassPathXmlApplicationContext**:该容器从 XML 文件中加载已被定义的 bean。在这里,你不需要提供 XML 文件的完整路径,只需正确配置 CLASSPATH 环境变量即可,因为,容器会从 CLASSPATH 中搜索 bean 配置文件。
    • **WebXmlApplicationContext**:该容器会在一个 web 应用程序的范围内加载在 XML 文件中已被定义的 bean。

    使用 `FileSystemXmlApplicationContext` 获取 **bean** 对象

    1. 先生成工厂对象。加载完指定路径下**bean**配置文件后,利用框架提供的`FileSystemXmlApplicationContext`API 去生成工厂**bean****FileSystemXmlApplicationContext**负责生成和初始化所有的对象,比如,所有在 XML bean 配置文件中的 **bean**
    2. 利用上面生成的上下文中的 **getBean()** 方法得到所需要的 **bean**。 这个方法通过配置文件中的 bean ID 来返回一个真正的对象。一旦得到这个对象,就可以利用这个对象来调用任何方法。

    案例代码:
    Person.java

    1. package com.baklib.custom;
    2. public class Person {
    3. private String name;
    4. private String carType;
    5. public String getName() {
    6. return name;
    7. }
    8. public void setName(String name) {
    9. this.name = name;
    10. }
    11. public String getCarType() {
    12. return carType;
    13. }
    14. public void setCarType(String carType) {
    15. this.carType = carType;
    16. }
    17. public void buyCar(){
    18. System.out.println(this.getName()+"购买了"+this.getCarType()+"!");
    19. }
    20. }

    MainAPP.java

    1. package com.baklib.custom;
    2. import org.springframework.context.ApplicationContext;
    3. import org.springframework.context.support.FileSystemXmlApplicationContext;
    4. public class MainApp {
    5. public static void main(String[] args) {
    6. // 绝对路径获取 Bean 配置文件
    7. ApplicationContext context = new FileSystemXmlApplicationContext
    8. ("C:/project/Java/Spring/SpringPractice/src/main/resources/Beans.xml");
    9. // 相对路径获取 Bean 配置文件
    10. // ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml");
    11. Person person = (Person) context.getBean("person");
    12. person.setCarType("小轿车");
    13. person.buyCar();
    14. }
    15. }

    配置文件 Beans.xml

    1. <?xml version="1.0" encoding="UTF-8"?>
    2. <beans xmlns="http://www.springframework.org/schema/beans"
    3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    4. xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
    5. <bean id="person" class="com.baklib.custom.Person">
    6. <property name="name" value="张三" />
    7. <property name="carType" value="" />
    8. </bean>
    9. </beans>

    编写完以上代码,就可以运行这个程序,运行结束后,可以在控制台看到下面的信息

    1. 张三购买了小轿车!