一、前言
学习Spring已经有一段时间了,一直对spring的源码比较好奇,因此开始准备对Spring的源码进行学习。这篇就从最简单的HelloWord开始
二、分析
Java代码
public class Person {
public Person() {
System.out.println("Person execute");
}
private String name ;
private Integer id ;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
}
applicationContext.xml
<bean name="personName1" class="com.lw.spring.bean.Person" id="person1"></bean>
测试
public class Test {
@SuppressWarnings("deprecation")
public static void main(String[] args) {
BeanFactory bf = new XmlBeanFactory(new ClassPathResource("applicationContext.xml"));
Person p = (Person) bf.getBean("person1");
System.out.println(p);
}
}
我们平常使用更多的应该是如下的加载方式
ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
其实BeanFactory才是整个IOC容器的祖宗。其它的不过是对其补充。
- XmlBeanFactory:自定义XML读取器,下面会介绍到.
- ApplicationContext:这其实又是一个体系的IOC容器了,只不过比较高级,后面会写文章介绍到.
源码分析
public XmlBeanFactory(Resource resource) throws BeansException {
this(resource, null);
}
public XmlBeanFactory(Resource resource, BeanFactory parentBeanFactory) throws BeansException {
super(parentBeanFactory);
// 这个reader就是XMLBeanFactory对其父类DefaultListableBeanFactory的补充
this.reader.loadBeanDefinitions(resource);
}
我们可以看看整个XMLBeanFactory的整个代码,可以发现整个XMLBeanFactory除了添加了个XmlBeanDefinitionReader 之外,并没有添加其它什么东西.
public class XmlBeanFactory extends DefaultListableBeanFactory {
private final XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(this);
public XmlBeanFactory(Resource resource) throws BeansException {
this(resource, null);
}
public XmlBeanFactory(Resource resource, BeanFactory parentBeanFactory) throws BeansException {
super(parentBeanFactory);
this.reader.loadBeanDefinitions(resource);
}
}
下面进入到读取器XmlBeanDefinitionReader 的代码
@Override
public int loadBeanDefinitions(Resource resource) throws BeanDefinitionStoreException {
return loadBeanDefinitions(new EncodedResource(resource));
}
private final ThreadLocal<Set<EncodedResource>> resourcesCurrentlyBeingLoaded =
new NamedThreadLocal<Set<EncodedResource>>("XML bean definition resources currently being loaded");
public int loadBeanDefinitions(EncodedResource encodedResource) throws BeanDefinitionStoreException {
Assert.notNull(encodedResource, "EncodedResource must not be null");
if (logger.isInfoEnabled()) {
logger.info("Loading XML bean definitions from " + encodedResource.getResource());
}
// 通过本地线程获取一个封装EncodedResource的Set集合
Set<EncodedResource> currentResources = this.resourcesCurrentlyBeingLoaded.get();
if (currentResources == null) {
// 如果为null,则创建并且绑定当前线程
currentResources = new HashSet<EncodedResource>(4);
this.resourcesCurrentlyBeingLoaded.set(currentResources);
}
// 将applicationContext.xml添加到集合当中
if (!currentResources.add(encodedResource)) {
throw new BeanDefinitionStoreException(
"Detected cyclic loading of " + encodedResource + " - check your import definitions!");
}
try {
InputStream inputStream = encodedResource.getResource().getInputStream();
try {
InputSource inputSource = new InputSource(inputStream);
if (encodedResource.getEncoding() != null) {
inputSource.setEncoding(encodedResource.getEncoding());
}
// 加载BeanDefinition
return doLoadBeanDefinitions(inputSource, encodedResource.getResource());
}
finally {
inputStream.close();
}
}
catch (IOException ex) {
throw new BeanDefinitionStoreException(
"IOException parsing XML document from " + encodedResource.getResource(), ex);
}
finally {
currentResources.remove(encodedResource);
if (currentResources.isEmpty()) {
this.resourcesCurrentlyBeingLoaded.remove();
}
}
}
比较重要的地方做了注释.其中BeanDefinition其实就是<bean/>标签在Spring内部的表现形式.
protected int doLoadBeanDefinitions(InputSource inputSource, Resource resource)
throws BeanDefinitionStoreException {
try {
// 加载Document文档
Document doc = doLoadDocument(inputSource, resource);
// 注册BeanDefinition
return registerBeanDefinitions(doc, resource);
}
catch (Exception ex) {
// some exception
}
}
上面第一步加载Document使用的sax解析,就不详细看,主要来看注册BeanDefinition.
public int registerBeanDefinitions(Document doc, Resource resource) throws BeanDefinitionStoreException {
BeanDefinitionDocumentReader documentReader = createBeanDefinitionDocumentReader();
int countBefore = getRegistry().getBeanDefinitionCount();
documentReader.registerBeanDefinitions(doc, createReaderContext(resource));
return getRegistry().getBeanDefinitionCount() - countBefore;
}
继续
@Override
public void registerBeanDefinitions(Document doc, XmlReaderContext readerContext) {
this.readerContext = readerContext;
logger.debug("Loading bean definitions");
Element root = doc.getDocumentElement();
doRegisterBeanDefinitions(root);
}
protected void doRegisterBeanDefinitions(Element root) {
BeanDefinitionParserDelegate parent = this.delegate;
this.delegate = createDelegate(getReaderContext(), root, parent);
if (this.delegate.isDefaultNamespace(root)) {
String profileSpec = root.getAttribute(PROFILE_ATTRIBUTE);
if (StringUtils.hasText(profileSpec)) {
String[] specifiedProfiles = StringUtils.tokenizeToStringArray(
profileSpec, BeanDefinitionParserDelegate.MULTI_VALUE_ATTRIBUTE_DELIMITERS);
if (!getReaderContext().getEnvironment().acceptsProfiles(specifiedProfiles)) {
return;
}
}
}
// 解析BeanDefinition之前应该做的操作,空方法
preProcessXml(root);
// 解析BeanDefinition
parseBeanDefinitions(root, this.delegate);
// 解析BeanDefinition之后应该做的操作,空方法
postProcessXml(root);
this.delegate = parent;
}
protected void parseBeanDefinitions(Element root, BeanDefinitionParserDelegate delegate) {
if (delegate.isDefaultNamespace(root)) {
NodeList nl = root.getChildNodes();
for (int i = 0; i < nl.getLength(); i++) {
Node node = nl.item(i);
if (node instanceof Element) {
Element ele = (Element) node;
if (delegate.isDefaultNamespace(ele)) {
// 解析默认标签
parseDefaultElement(ele, delegate);
}
else {
// 解析用户自定义标签
delegate.parseCustomElement(ele);
}
}
}
}
else {
delegate.parseCustomElement(root);
}
}
上面解析默认标签其实就是bean、import之类的了。解析标签时候同时也会解析其属性,由于太过复杂,就没有深入下去了。
BeanDefinition
上面提到过<bean/>标签在Spring内部的表现形式其实就是BeanDefinition,而BeanDefinition只是一个接口,它有哪些实现类呢?
- ChildBeanDefinition
- GenericBeanDefinition
- RootBeanDefinition
其中RootBeanDefinition就是我们通常的bean了。
OK、这篇就简单到这里了。其实这里只是简单的分析一行代码,下一篇将会分析Bean是如何获取的。