先看下BeanFactory的調用過程
public class BeanFactoryTest {
public static void main(String[] args) {
ClassPathResource res = new ClassPathResource("beans.xml");
XmlBeanFactory factory = new XmlBeanFactory(res);
Object obj = factory.getBean("beanFactory");
System.out.println(obj.getClass());
}
}
beans.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-2.5.xsd">
<bean id="beanFactory" class="com.hz.yk.spring.test.BeanFactoryTest" />
</beans>
就是簡單的定義下自己。
ClassPathResource的構造函數跟進去看,其實就是對本地path和classload進行設置,爲下一步做好準備。
public ClassPathResource(String path, ClassLoader classLoader) {
Assert.notNull(path, "Path must not be null");
String pathToUse = StringUtils.cleanPath(path);
if (pathToUse.startsWith("/")) {
pathToUse = pathToUse.substring(1);
}
this.path = pathToUse;
this.classLoader = (classLoader != null ? classLoader : ClassUtils.getDefaultClassLoader());
}
先看下ClassPathResource 的類圖
Resource其實就封裝了對文件的定位,並封裝成spring定義的訪問接口。具體看下getInputStream(),getFile()等方法的實現。
可以看到資源的定位其實挺沒花頭的,下一節將研究bean的解析