Spring 源码阅读之BeanFactory

1. BeanFactory 的结构体系如下:

Spring 源码阅读之BeanFactory_第1张图片

2. XmlBeanFactory ,装载Spring配置信息

package org.springframework.beans.factory.xml;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.core.io.Resource;

public class XmlBeanFactory extends DefaultListableBeanFactory {

    private final XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(this);


    /**
     * Create a new XmlBeanFactory with the given resource,
     * which must be parsable using DOM.
     * @param resource XML resource to load bean definitions from
     * @throws BeansException in case of loading or parsing errors
     */
    public XmlBeanFactory(Resource resource) throws BeansException {
        this(resource, null);
    }

    /**
     * Create a new XmlBeanFactory with the given input stream,
     * which must be parsable using DOM.
     * @param resource XML resource to load bean definitions from
     * @param parentBeanFactory parent bean factory
     * @throws BeansException in case of loading or parsing errors
     */
    public XmlBeanFactory(Resource resource, BeanFactory parentBeanFactory) throws BeansException {
        super(parentBeanFactory);
        this.reader.loadBeanDefinitions(resource);
    }

}

3. BeanFactory 接口

package org.springframework.beans.factory;

import org.springframework.beans.BeansException;


public interface BeanFactory {

    
    String FACTORY_BEAN_PREFIX = "&";


    Object getBean(String name) throws BeansException;

    
    <T> T getBean(String name, Class<T> requiredType) throws BeansException;

    
    <T> T getBean(Class<T> requiredType) throws BeansException;

    
    Object getBean(String name, Object... args) throws BeansException;

    
    boolean containsBean(String name);

    
    boolean isSingleton(String name) throws NoSuchBeanDefinitionException;

    
    boolean isPrototype(String name) throws NoSuchBeanDefinitionException;

    
    boolean isTypeMatch(String name, Class targetType) throws NoSuchBeanDefinitionException;

    
    Class<?> getType(String name) throws NoSuchBeanDefinitionException;

    
    String[] getAliases(String name);

}

4. 运用实例:

Resource reource = null;//load spring configure file
BeanFactory bf = new XmlBeanFactory(reource);
bf.getBean("beanName");

你可能感兴趣的:(beanfactory)