例如学生类:

package com.test.bean;
 
public class Student {
    public void hello(){
        System.out.println("Hello World!");
    }
}

由 Bean 管理对象后,我们就不需要手动 new 对象,而是在spring配置文件中编写:

<bean name="student" class="com.test.bean.Student"/>

此时,IoC容器就会自动创建并进行提供,我们可以直接从 context 中使用 getBean 方法获得对象:

public static void main(String[] args) {
    ApplicationContext context = new ClassPathXmlApplicationContext("test.xml");
    Student student = (Student) context.getBean("student");   //使用getBean方法来获取对应的对象(Bean)
    student.hello();
}