1. 程式人生 > >Spring Ioc 原始碼分析之Bean的載入和構造

Spring Ioc 原始碼分析之Bean的載入和構造

我們都知道,Spring Ioc和Aop是Spring的核心的功能,因此花一點時間去研究還是很有意義的,如果僅僅是知其所以然,也就體會不到大師設計Spring的精華,還記得那句話,Spring為JavaEE開發帶來了春天。
IOC就是Inversion of control 也就是控制反轉的意思,另一種稱呼叫做依賴注入,這個可能更直觀一點,拿個例子來說吧:

@Component
public class UserService {
    @Autowired
    private UserMapper mapper;
}

比如在UserService可能要呼叫一個Mapper,這個Mapper去做DAO的操作,在這裡我們直接通過@Autowired註解去注入這個Mapper,這個就叫做依賴注入,你想要什麼就注入什麼,不過前提它是一個Bean。至於是怎麼注入的,那是Spring容器做的事情,也是我們今天去探索的。
在進行分析之前,我先宣告一下,下面的這些程式碼並不是從spring 原始碼中直接拿過來,而是通過一步步簡化,抽取spring原始碼的精華,如果直接貼原始碼,我覺得可能很多人都會被嚇跑,而且還不一定能夠學到真正的東西。
Spring要去管理Bean首先要把Bean放到容器裡,那麼Spring是如何獲得Bean的呢?

首先,Spring有一個數據結構,BeanDefinition,這裡存放的是Bean的內容和元資料,儲存在BeanFactory當中,包裝Bean的實體:

public class BeanDefinition {
    //真正的Bean例項
    private Object bean;
    //Bean的型別資訊
    private Class beanClass;
    //Bean型別資訊的名字
    private String beanClassName;
    //用於bean的屬性注入 因為Bean可能有很多熟屬性
    //所以這裡用列表來進行管理
    private PropertyValues propertyValues = new PropertyValues();
}

PerpertyValues存放Bean的所有屬性

public class PropertyValues {
    private final List<PropertyValue> propertyValueList = new ArrayList<PropertyValue>();
}

PropertyValue存放的是每個屬性,可以看到兩個欄位,name和valu。name存放的就是屬性名稱,value是object型別,可以是任何型別

public class PropertyValue {
    private final String name;
    private final Object value;
}

定義好這些資料結構了,把Bean裝進容器的過程,其實就是其BeanDefinition構造的過程,那麼怎麼把一些類裝入的Spring容器呢?

Spring有個介面就是獲取某個資源的輸入流,獲取這個輸入流後就可以進一步處理了:

public interface Resource {
    InputStream getInputStream() throws IOException;
}

UrlResource 是對Resource功能的進一步擴充套件,通過拿到一個URL獲取輸入流。

public class UrlResource implements Resource {
    private final URL url;
    public UrlResource(URL url) {
        this.url = url;
    }
    @Override
    public InputStream getInputStream() throws IOException{
        URLConnection urlConnection = url.openConnection();
        urlConnection.connect();
        return urlConnection.getInputStream();
    }

ResourceLoader是資源載入的主要方法,通過location定位Resource,
然後通過上面的UrlResource獲取輸入流:

public class ResourceLoader {
    public Resource getResource(String location){
        URL resource = this.getClass().getClassLoader().getResource(location);
        return new UrlResource(resource);
    }
}

大家可能會對上面的這段程式碼產生疑問:

    URL resource = this.getClass().getClassLoader().getResource(location);

為什麼通過得到一個類的類型別,然後得到對應的類載入器,然後呼叫類載入器的Reource怎麼就得到了URL這種型別呢?
我們來看一下類載入器的這個方法:

public URL getResource(String name) {
        URL url;
        if (parent != null) {
            url = parent.getResource(name);
        } else {
            url = getBootstrapResource(name);
        }
        if (url == null) {
            url = findResource(name);
        }
        return url;
    }

從這個方法中我們可以看出,類載入器去載入資源的時候,先會去讓父類載入器去載入,如果父類載入器沒有的話,會讓根載入器去載入,如果這兩個都沒有載入成功,那就自己嘗試去載入,這個一方面為了java程式的安全性,不可能你使用者自己隨便寫一個載入器,就用你使用者的。

接下來我們看一下重要角色,這個是載入BeanDefinition用的。

public interface BeanDefinitionReader {
    void loadBeanDefinitions(String location) throws Exception;
}

這個介面是用來從配置中讀取BeanDefinition:
其中registry key是bean的id,value存放資源中所有的BeanDefinition

public abstract class AbstractBeanDefinitionReader implements BeanDefinitionReader {

    private Map<String,BeanDefinition> registry;

    private ResourceLoader resourceLoader;

    protected AbstractBeanDefinitionReader(ResourceLoader resourceLoader) {
        this.registry = new HashMap<String, BeanDefinition>();
        this.resourceLoader = resourceLoader;
    }

    public Map<String, BeanDefinition> getRegistry() {
        return registry;
    }

    public ResourceLoader getResourceLoader() {
        return resourceLoader;
    }
}

最後我們來看一個通過讀取Xml檔案的BeanDefinitionReader:

public class XmlBeanDefinitionReader extends AbstractBeanDefinitionReader {
    /**
     * 建構函式 傳入我們之前分析過的ResourceLoader 這個通過
     * location 可以 載入到Resource
     */
    public XmlBeanDefinitionReader(ResourceLoader resourceLoader) {
        super(resourceLoader);
    }

    /**
     * 這個方法其實是BeanDefinitionReader這個介面中的方法
     * 作用就是通過location來構造BeanDefinition
     */
    @Override
    public void loadBeanDefinitions(String location) throws Exception {
        //把location傳給ResourceLoader拿到Resource,然後獲取輸入流
        InputStream inputStream = getResourceLoader().getResource(location).getInputStream();
        //接下來進行輸入流的處理
        doLoadBeanDefinitions(inputStream);
    }

    protected void doLoadBeanDefinitions(InputStream inputStream) throws Exception {
        //因為xml是文件物件,所以下面進行一些處理文件工具的構造
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = factory.newDocumentBuilder();
        //把輸入流解析成一個文件,java可以處理的文件
        Document doc = docBuilder.parse(inputStream);
        // 處理這個文件物件 也就是解析bean
        registerBeanDefinitions(doc);
        inputStream.close();
    }

    public void registerBeanDefinitions(Document doc) {
        //得到文件的根節點,知道根節點後獲取子節點就是通過層級關係處理就行了
        Element root = doc.getDocumentElement();
        //解析根節點 xml的根節點
        parseBeanDefinitions(root);
    }

    protected void parseBeanDefinitions(Element root) {
        NodeList nl = root.getChildNodes();
        for (int i = 0; i < nl.getLength(); i++) {
            Node node = nl.item(i);
            //element有屬性的包裝
            if (node instanceof Element) {
                Element ele = (Element) node;
                processBeanDefinition(ele);
            }
        }
    }

    protected void processBeanDefinition(Element ele) {
        /**
         *  <bean id="object***" class="com.***.***"/>
         */
        //獲取element的id
        String name = ele.getAttribute("id");
        //獲取element的class
        String className = ele.getAttribute("class");
        BeanDefinition beanDefinition = new BeanDefinition();
        //處理這個bean的屬性
        processProperty(ele, beanDefinition);
        //設定BeanDefinition的類名稱
        beanDefinition.setBeanClassName(className);
        //registry是一個map,存放所有的beanDefinition
        getRegistry().put(name, beanDefinition);
    }

    private void processProperty(Element ele, BeanDefinition beanDefinition) {
        /**
         *類似這種:
         <bean id="userServiceImpl" class="com.serviceImpl.UserServiceImpl">
         <property name="userDao" ref="userDaoImpl"> </property>
         </bean>
         */
        NodeList propertyNode = ele.getElementsByTagName("property");
        for (int i = 0; i < propertyNode.getLength(); i++) {
            Node node = propertyNode.item(i);
            if (node instanceof Element) {
                Element propertyEle = (Element) node;
                //獲得屬性的名稱
                String name = propertyEle.getAttribute("name");
                //獲取屬性的值
                String value = propertyEle.getAttribute("value");
                if (value != null && value.length() > 0) {
                    //設定這個bean對應definition裡的屬性值
                    beanDefinition.getPropertyValues().addPropertyValue(new PropertyValue(name, value));
                } else {
                    //value是Reference的話  就會進入到這裡處理
                    String ref = propertyEle.getAttribute("ref");
                    if (ref == null || ref.length() == 0) {
                        throw new IllegalArgumentException("Configuration problem: <property> element for property '"
                                + name + "' must specify a ref or value");
                    }
                    //構造一個BeanReference 然後把這個引用方到屬性list裡
                    BeanReference beanReference = new BeanReference(ref);
                    beanDefinition.getPropertyValues().addPropertyValue(new PropertyValue(name, beanReference));
                }
            }
        }
    }
}

上面用到了BeanReference(如下),其實這個和PropertyValue類似,用不同的型別是為了更好的區分:

public class BeanReference {
     private String name;
     private Object bean;
}

好了,到現在我們已經分析完了Spring是如何找到Bean並載入進入Spring容器的,這裡面最主要的資料結構就是BeanDefinition,ReourceLoader來完成資源的定位,讀入,然後獲取輸入流,進一步的處理,這個過程中有對xml文件的解析和對屬性的填充。