在上一篇文章中,我们学习了IoC与DI的相关概念与原理,现在让我们 以HelloWorld为例,编写一个程序,让创建对象的工作由Spring帮助我们创建。 一同感受一下Spring框架带给我们开发的便捷性。

public class HelloWorld {
    private String name;
    public void setName(String name) {
        this.name = name;
    }
    public void sayHi(){
        System.out.println(name + ",HelloWorld!");
    }
}
 
@Test
public void testSayHi() throws Exception{
    HelloWorld helloWorld = new HelloWorld();
    helloWorld.setName("段康家");
    helloWorld.sayHi();
}
 
这种做法是以前最常用的做法,HelloWorld这个类的对象是我们程序员自己去创建并为属性赋值,但是要使用Spring,该如何实现同样的功能呢?看4.3以后的章节。
org.springframework spring-context 5.2.1.RELEASE junit junit 4.12 test 
说明:主配置文件的名称一般叫beans.xml或在applicationContext.xml
在resources目录下新建beans.xml文件。
@Test
public void testSayHi() throws Exception{
    // 1、读取主配置文件信息,获取核心容器对象
    ApplicationContext ac = new ClassPathXmlApplicationContext("beans.xml");
    // 2、从容器中根据id获取对象(bean)
    HelloWorld helloWorld = (HelloWorld) ac.getBean("helloWorld");
    // 3、调用bean的方法
    helloWorld.sayHi();
}
 
ClassPathXmlApplicationContext
该类可以加载类路径下的配置文件,要求配置文件必须在类路径下。不在的话,加载不了。
FileSystemXmlApplicationContext
它可以加载磁盘任意路径下的配置文件。
AnnotationConfigApplicationContext
它是用于读取注解创建容器的
 是Spring里面最底层的接口,提供了最简单的容器的功能,只提供了实例化对象和拿对象的功能。
 BeanFactory在启动的时候不会去实例化Bean,只有从容器中拿Bean的时候才会去实例化。延迟加载
public class UserServiceImpl {
    public UserServiceImpl(){
        System.out.println("对象的构造方法执行了");
    }
}
 
@Test
public void testUserServiceImpl() throws Exception{
        // 加载配置文件创建容器并不会导致bean的立即初始化
        Resource resource = new ClassPathResource("beans.xml");
        BeanFactory bf = new XmlBeanFactory(resource);
        // 只有再去真正要使用的某个bean的时候才会初始化
        UserServiceImpl userService = (UserServiceImpl) bf.getBean("userService");
        System.out.println(userService);
}
 
 应用上下文,该接口其实是BeanFactory的子接口,提供了更多的有用的功能:
ApplicationContext在启动的时候就把所有的Bean全部实例化了。
