Spring Ioc 源碼分析之Bean的加載和構造
IOC就是Inversion of control 也就是控制反轉的意思,另一種稱呼叫做依賴註入,這個可能更直觀一點,拿個例子來說吧:
@Component
public class UserService {
@Autowired
private UserMapper mapper;
}
比如在UserService可能要調用一個Mapper,這個Mapper去做DAO的操作,在這裏我們直接通過@Autowired註解去註入這個Mapper,這個就叫做依賴註入,你想要什麽就註入什麽,不過前提它是一個Bean。至於是怎麽註入的,那是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文檔的解析和對屬性的填充。
Spring Ioc 源碼分析之Bean的加載和構造