Spring 学习笔记(二)—— IOC 容器(BeanFactory)

  使用Spring IoC容器后,容器会自动对被管理对象进行初始化并完成对象之间的依赖关系的维护,在被管理对象中无须调用Spring的API。

  为了实现IoC功能,Spring提供了两个访问接口:

  •   org.springframework.beans.factory.BeanFactory
  •   org.springframework.context.ApplicationContext

  前者为Bean工厂,借助于配置文件能够实现对JavaBean的配置和管理,用于向使用者提供Bean的实例;

  后者为ApplicationContext,其构建在BeanFactory基础上,辞工了更多的实用功能。


  注意:

    Spring中将IoC容器管理的对象称为Bean,这与传统的JavaBean不完全相同,只是借用了Bean的名称。


  BeanFactory

    BeanFactory作为制造Bean的工厂,BeanFactory接口负责向容器的使用者提供实例,其主要功能是完成容器管理对象的实例化。

    常用的方法:

方法 功能描述
boolean containsBean(String name) 判断Spring容器是否包含ID为name的Bean对象
Object getBean(String name) 返回容器ID为name的Bean对象
Object getBean(String name,Class requiredType) 返回容器中ID为name、类型为requiredType的Bean
Class getType(String name) 返回容器中ID为name的Bean的类型

    

    例:

    创建一个bean.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="book" class="IoCDemo.Book">
           <property name="name" value="SSH开发"/>
           <property name="author" value="rekent"/>
           <property name="publishHouse" value="publisher"/>
           <property name="price" value="70"/>
       </bean>
</beans>

  再创建一个Book的JavaBean,以及一个测试,BeanFactoryExample.java

package IoCDemo;

import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.factory.xml.XmlBeanDefinitionReader;
import org.springframework.core.io.ClassPathResource;

/**
 * Created by Richard Cheung on 2017/7/23.
 */
public class BeanFactoryExample {
    public static void main(String[] args){
        ClassPathResource resource=new ClassPathResource("IocDemo/Bean.xml");
        DefaultListableBeanFactory factory=new DefaultListableBeanFactory();
        XmlBeanDefinitionReader reader=new XmlBeanDefinitionReader(factory);
        reader.loadBeanDefinitions(resource);
        Book book= (Book) factory.getBean("book");
        System.out.println(book.getName());
        System.out.println(book.getAuthor());
        System.out.print(book.getPublishHouse());
    }


}

  输出结果为:

…………
信息: Loading XML bean definitions from class path resource [IocDemo/Bean.xml]
SSH开发
rekent
publisher
Process finished with exit code 0

  首先使用ClassPathResource类指定了配置文件是位于类路径下的bean.xml

  然后构造了DefaultListableBeanFactory对象,并将DefaultListableBeanFactory对象传递给新构造的XmlBeanDefinitionReader对象。

  通过XmlBeanDefinitionReader对象加载了配置文件。

  最后通过DefaultListableBeanFactory中的getBean()方法从IoC容器中获取了Bean。

原文地址:https://www.cnblogs.com/rekent/p/7226538.html