最近在學習spring過程中,有人問我爲什麼使用<ref bean>標籤時總是顯示bean未定義。
爲了解決這個問題,就要分析一下bean的加載機制和<ref bean>的作用範圍。
首先,<ref bean>查找的範圍有兩個,一個是當前xml文檔,另一個是和它屬於同一BeanFactory中的其他javabean。
而對於bean的加載,以scope爲單例爲例,bean是在ApplicationContext對象創建時調用。
例如ApplicationContext context = new ClassXmlApplicationContext("a.xml");
那麼這個時候只有a中的bean對象被創建,a 中的<ref bean>只能在a中查找。
而如果是ApplicationContext context = new ClassXmlApplicationContext("a.xml",”b.xml“);
a中的<ref bean>就可以在a和b中查找bean對象。
所以如果顯示bean未定義時,就要注意bean的xml文件是否處於同一個ApplicationContext對象中。