天天看点

Spring IoC容器Spring IoC容器Spring IoC接口ApplicationContext重要实现类装配Bean的方式

文章目录

  • Spring IoC容器
  • Spring IoC接口
  • ApplicationContext重要实现类
  • 装配Bean的方式

Spring IoC容器

前面说到要从Spring那里得到好处就要将对象交给Spring管理。在Spring中,这些被管理的对象被称为Bean,将Bean的创建和依赖关系交给Spring管理,我们就说对象被控制反转(Inversion Of Controll, IoC)了,而容纳这些Bean的容器则称为Spring IoC容器。

既然要将对象(Bean)交给Spring IoC容器管理,那么就要通过Spring定义的规则将对象存放到Spring IoC容器。Spring IoC容器的设计主要是基于BeanFactory和ApplicationContext两个接口,其中ApplicationContext是BeanFactory的子接口之一,换句话说BeanFactory是Spring IoC容中存在的所定义的最底层接口,而ApplicationContext是其高级接口之一,并且对BeanFactory功能做了许多有用的扩展。在绝大部分的场景下,都会使用ApplicationContext作为Spring IoC容器。以下为简要类图:

Spring IoC容器Spring IoC容器Spring IoC接口ApplicationContext重要实现类装配Bean的方式

Spring IoC接口

我们来看看BeanFactory接口中定义的方法:

Spring IoC容器Spring IoC容器Spring IoC接口ApplicationContext重要实现类装配Bean的方式
  • getBean(..)

    方法用于从Spring IoC容器中获取Bean,getBean方法有五个重载方法,带有String参数的用于指定Bean的名称,带有Class参数的用于指定Bean的类型。若仅指定名称(默认名称为类名首字母小写),则返回的对象为Object,需要进行类型转换;若仅指定类型,则返回该类型的对象,而无需进行转换。可以看出,仅指定类型的方法会存在使用父类类型无法准确获得实例的异常,比如下面一段代码:
    public interface Person {
        public void eat();
    }
    
    class Student implements Person{
        public void eat() {}
    }
    
    class Teacher implements Person{
        public void eat() {}
    }
               
    若通过

    getBean(Person.class)

    方法来获取实例,那得到的是Student的实例呢还是Teacher的实例呢?无法判断,所以就会抛出异常。
  • isSingleton(String)

    用于判断是否为单例,如果为真,则该Bean在容器中是作为一个唯一单例存在的。即不管调用几次

    getBean("student")

    方法获取Student的实例都是同一个对象。
  • isPrototype(String)

    则与

    isSingleton(String)

    相反,每次获取Bean都是一个新的实例。
  • getAliases(String)

    方法是获取别名的方法。

ApplicationContext重要实现类

ApplicationContext接口有两个重要的实现类,ClassPathXmlApplicationContext和AnnotationConfigApplicationContext,分别用于从xml文件中读取Bean配置和从注解读取Bean配置。以下为类图:

Spring IoC容器Spring IoC容器Spring IoC接口ApplicationContext重要实现类装配Bean的方式

装配Bean的方式

  1. 通过注解装配Bean
    • @Component注解
    • @Bean注解
    • @Autowired自动装配
  2. 通过XML文件配置装配Bean
    • 通过构造器装配
    • 通过属性装配
  3. 注解和XML文件混合装配

下一篇——使用注解装配Bean

继续阅读