IOC(Inversion of Control) 控制反转:所谓控制反转,就是把原先我们代码里面需要实现的对象创建、依赖的代码,反转给容器来帮忙实现。呢么必然我们需要创建一个容器,同时需要一种描述来让容器知道需要创建的对象与对象的关系。这个描述最具体表现就是我们所看到的配置文件。 DI(Dependency Injection)依赖注入:就是指对象是被动接受依赖而不是自己主动去找,换句话说就是只对象不是从容器中查找它依赖的类,而是在容器实例化对象的时候主动将它依赖的类注入给它。
基于XMl的IOC容器初始化 IOC容器的初始化包括BeanDefinition的Resource定位、加载和注册三个基本的过程。ApplicationContext系列的容器是我们最熟悉的,因此web项目中使用的XmlWebApplicationContext就属于这个继承体系,还有ClasspathXmlApplicationContext等,其继承体系如下图所示:
«interface»
ListableBeanFactory
«interface»
HierarchicalBeanFactory
«interface»
ApplicationContext
«interface»
ConfigurableApplicationContext
«interface»
WebApplicationContext
«interface»
ConfigurableWebApplicationContext
AbstractApplicationContext
AbstractRefreshableApplicationContext
AbstractXmlApplicationContext
ClassPathXmlApplicationContext
FileSystemXmlApplicationContext
AbstractRefreshableWebApplicationContext
XmlWebApplicationContext
AbstractRefreshableConfigApplicationContext
ApplicationContext允许上下文嵌套,通过保持父上下文可以维持一个上下文体系。对于Bean的查找可以在这个上下文体系中发生,首先插件当前上下文,其次是父上下文,逐级向上,这样为不同的Spring应用提供了一个共享的Bean定义环境。
PathMatchingResourcePatternResolver AbstractApplicationContext AbstractRefreshableApplicationContext AbstractRefreshableConfigApplicationContext AbstractXmlApplicationContext ClassPathXmlApplication Main PathMatchingResourcePatternResolver AbstractApplicationContext AbstractRefreshableApplicationContext AbstractRefreshableConfigApplicationContext AbstractXmlApplicationContext ClassPathXmlApplication Main new ClassPathXmlApplication("application.xml") 1 ClassPathXmlApplicationContext(String[],boolean,applicationContext) 2 super(parent) 3 super(parent) 4 super(parent) 5 super(parent) 6 this() 7 getResourcePatternResolver() 8 new() 9 setParent(parent) 10 setConfigLocations(configLocations) 11 refresh() 12 refresh() 13 prepareRefresh() 14 obtainFreshBeanFactory() 15 prepareBeanFactory(beanFactory) 16 postProcessBeanFactory(beanFactory) 17 invokeBeanFactoryPostProcessors(beanFactory) 18 registerBeanPostProcessors(beanFactory) 19 initMessageSource() 20 initApplicationEventMulticaster() 21 onRefresh() 22 registerListeners() 23 finishBeanFactoryInitialization(beanFactory) 24 finishRefresh() 25 destroyBeans() 26 cancelRefresh(ex) 27 resetCommonCaches() 28 我们通过main方法中的new ClassPathXmlApplication("application.xml")
作为入口,我们看到 super(parent)
最终调用了AbstractApplicationContext的AbstractApplicationContext(@Nullable ApplicationContext parent)
构造方法,里面调用了空参构造器加载了PathMatchingResourcePatternResolver
资源解析器;而setParent(ApplicationContext)
将父子级的上下文内容合并了起来。 setConfigLocations(configLocations)
设置此应用程序上下文的配置位置,如果未设置,则使用默认值。
SpringIOC容器对Bean配置资源的载入是从refresh()
函数开始的,这是一个模板方法,规定了IOC容器的启动流程,如下:
prepareRefresh()
:调用容器准备刷新的方法,获取容器的当前时间,同时给容器设置同步标识。
obtainFreshBeanFactory()
:告诉子类启动refreshBeanFactory()
方法,Bean定义资源文件的载入。
prepareBeanFactory(beanFactory)
:为BeanFactory配置容器特性,例如类加载器、事件处理器等。
postProcessBeanFactory(BeanFactory)
:为容器的某些子类指定特殊的BeanPost事件处理器。
invokeBeanFactoryPostProcessors(beanFactory)
:调用所有注册的BeanFactoryPostprocessor的Bean。
registerBeanPostProcessors(beanFactory)
:为BeanFactory注册BeanPost时间处理器,用于监听容器出发的事件。
initMessageSource()
:初始化信息源,和国际化相关。
initApplicationEventMulticaster()
:初始化容器事件传播器。
onRefresh()
:调用子类的某些特殊Bean初始化方法。
registerListeners()
:为事件传播注册事件监听器。
finishBeanFactoryInitialization(beanFactory)
:初始化所有剩余的单例Bean。
finishRefresh()
:初始化容器的生命周期事件处理器,并发布容器的生命周期事件。
destroyBeans()
:销毁已创建的Bean
cancelRefresh(ex)
:取消refresh操作,重置容器的同步标识。
resetCommonCaches()
:重置公共缓存。
创建容器 AbstractXmlApplicationContext AbstractApplicaitonContext AbstractRefreshableApplicationContext AbstractApplicationContext AbstractXmlApplicationContext AbstractApplicaitonContext AbstractRefreshableApplicationContext AbstractApplicationContext obtainFreshBeanFactory() refreshBeanFactory() destroyBeans() closeBeanFactory() createBeanFactory() customizeBeanFactory() loadBeanDefinitions() loadBeanDefinitions() initBeanDefinitionReader(beanDefinitionReader) loadBeanDefinitions(beanDefinitionReader) obtainFreshBeanFactory()
方法调用了子类容器refreshBeanFactory()
方法,启动容器载入Bean配置的信息过程, AbstractApplicationContext
类中只抽象定义了refreshBeanFactory()
方法,容器真正调用的是子类的AbstractRefreshableApplicationContext
实现的refreshBeanFactory()
方法,这个方法,先判断BeanFactory
是否存在,如果存在先销毁Beans
并关闭BeanFactory
,接着创建DefaultListableBeanFactory
,并调用loadBeanDefinitions(beanFactory)
装载bean定义。
载入配置路径 XmlBeanDefinitionReader(beanFactory) AbstractXmlApplicationContext Main XmlBeanDefinitionReader(beanFactory) AbstractXmlApplicationContext Main loadBeanDefinitions(DefaultListableBeanFactory) 1 new 2 initBeanDefinitionReader(beanDefinitionReader) 3 loadBeanDefinitions(beanDefinitionReader) 4 xmlBean读取器的其中一种策略XmlBeanDefinitionReader为例。XmlBeanDefinitionReader调用其夫泪AbstractBeanDefinitionReader的loadBeanDefinitions()方法读取Bean配置资源。
分配路径处理策略 XmlBeanDefinitionReader的抽象夫泪AbstractBeanDefinitionReader中定义了载入过程。
ResourcePatternResolver AbstractBeanDefinitionReader XmlBeanDefinitionReader Main ResourcePatternResolver AbstractBeanDefinitionReader XmlBeanDefinitionReader Main loadBeanDefinitions(string location) loadBeanDefinitions(String location) loadBeanDefinitions(String location, @Nullable Set<Resource> actualResources) getResource() 从AbstractBeanDefinitionReader
的loadBeanDefinitions()
方法源码分析可以看出该方法,调用资源加载器的获取资源方法resourceLoader.getResource(location)
,获取要加载的资源,而getResources()
方法其实定义在ResourcePatternResolver
中。所以我们有必要看一下ResourcePatternResolver
的全类图:
«interface»
ResourceLoader
DefaultResourceLoader
«interface»
ResourcePatternResolver
PathMatchingResourcePatternResolver
«interface»
ApplicationContext
«interface»
ConfigurableApplicationContext
AbstractApplicationContext
ServletContextResourcePatternResolver
FileSystemResourceLoader
ClassRelativeResourceLoader
ServletContextResourceLoader
AbstractRefreshableApplicationContext
AbstractRefreshableConfigApplicationContext
AbstractXmlApplicationContext
ClassPathXmlApplicationContext
FileSystemXmlApplicationContext
AbstractRefreshableWebApplicationContext
GroovyWebApplicationContext
AnnotationConfigWebApplicationContext
GenericApplicationContext
ComplexWebApplication
GenericWebApplicationContext
GenericGroovyApplicationContext
AnnotationConfigApplicationContext
GenericXmlApplicationContext
从上图可以看出最终的资源获取是通过ResourcePatternResolver中的getSource()方法获取,然后通过loadBeanDefinitions(source)方法加载配置信息,注册上下文的各种信息。
解析配置文件路径以ClassPathXmlApplicationContext
为例 ClassPathXmlApplication注册Bean时,需要通过DefaultResolverLoader中的getSource()方法,去获取资源resource,具体处理过程如下:
@Override
public Resource getResource(String location) {
Assert.notNull(location, "Location must not be null");
// 可以用预先添加好的协议处理
for (ProtocolResolver protocolResolver : this.protocolResolvers) {
Resource resource = protocolResolver.resolve(location, this);
if (resource != null) {
return resource;
}
}
// 如果类路径的方式,呢需要使用ClassPathResource来得到bean文件的资源对象。
if (location.startsWith("/")) {
return getResourceByPath(location);
}
else if (location.startsWith(CLASSPATH_URL_PREFIX)) {
return new ClassPathResource(location.substring(CLASSPATH_URL_PREFIX.length()), getClassLoader());
}
else {
try {
// Try to parse the location as a URL...
// 如果为URL方式,使用URLResource作为bean文件的资源对象
URL url = new URL(location);
return (ResourceUtils.isFileURL(url) ? new FileUrlResource(url) : new UrlResource(url));
}
catch (MalformedURLException ex) {
// No URL -> resolve as resource path.
// 如果既不是classpath标识,又不是URL表示的resource定位,则调用
// 容器本身的getResourceByPath方法获取Resource
return getResourceByPath(location);
}
}
}
开始读取配置内容 XmlBeanDefinitionReader Main XmlBeanDefinitionReader Main loadBeanDefinitions(Resource resource) loadBeanDefinitions(EncodedResource encodedResource) doLoadBeanDefinitions(InputSource inputSource, Resource resource)
@Override
public int loadBeanDefinitions(Resource resource) throws BeanDefinitionStoreException {
// 将读入的xml资源进行特殊编码处理
return loadBeanDefinitions(new EncodedResource(resource));
}
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());
}
Set<EncodedResource> currentResources = this.resourcesCurrentlyBeingLoaded.get();
if (currentResources == null) {
currentResources = new HashSet<>(4);
this.resourcesCurrentlyBeingLoaded.set(currentResources);
}
if (!currentResources.add(encodedResource)) {
throw new BeanDefinitionStoreException(
"Detected cyclic loading of " + encodedResource + " - check your import definitions!");
}
try {
// 将资源文件转为inputStream的IO流
InputStream inputStream = encodedResource.getResource().getInputStream();
try {
// 从InputStream中得到Xml的解析源
InputSource inputSource = new InputSource(inputStream);
if (encodedResource.getEncoding() != null) {
inputSource.setEncoding(encodedResource.getEncoding());
}
// 这里是读取过程
return doLoadBeanDefinitions(inputSource, encodedResource.getResource());
}
finally {
// 关闭从Resource中得到的IO流
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();
}
}
}
// 从特定的xml文件中实际载入bean配置资源的方法
protected int doLoadBeanDefinitions(InputSource inputSource, Resource resource)
throws BeanDefinitionStoreException {
try {
// 将XML文件转换为DOM对象,解析过程由documentLoader实现
Document doc = doLoadDocument(inputSource, resource);
// 这里是启动对Bean定义解析的详细过程,该解析过程会用到Spring的Bean配置规则。
return registerBeanDefinitions(doc, resource);
}
catch (BeanDefinitionStoreException ex) {
throw ex;
}
catch (SAXParseException ex) {
throw new XmlBeanDefinitionStoreException(resource.getDescription(),
"Line " + ex.getLineNumber() + " in XML document from " + resource + " is invalid", ex);
}
catch (SAXException ex) {
throw new XmlBeanDefinitionStoreException(resource.getDescription(),
"XML document from " + resource + " is invalid", ex);
}
catch (ParserConfigurationException ex) {
throw new BeanDefinitionStoreException(resource.getDescription(),
"Parser configuration exception parsing XML from " + resource, ex);
}
catch (IOException ex) {
throw new BeanDefinitionStoreException(resource.getDescription(),
"IOException parsing XML document from " + resource, ex);
}
catch (Throwable ex) {
throw new BeanDefinitionStoreException(resource.getDescription(),
"Unexpected exception parsing XML document from " + resource, ex);
}
}
通过源码可以看到,载入Bean配置信息的最后一步是将Bean配置信息转为Document对象。
准备文档对象 DefaultDocumentLoader将bean配置资源转换成Document对象的源码如下:
@Override
public Document loadDocument(InputSource inputSource, EntityResolver entityResolver,
ErrorHandler errorHandler, int validationMode, boolean namespaceAware) throws Exception {
// 创建文件解析器工厂
DocumentBuilderFactory factory = createDocumentBuilderFactory(validationMode, namespaceAware);
if (logger.isDebugEnabled()) {
logger.debug("Using JAXP provider [" + factory.getClass().getName() + "]");
}
// 创建文档解析器
DocumentBuilder builder = createDocumentBuilder(factory, entityResolver, errorHandler);
// 解析Spring的Bean配置资源
return builder.parse(inputSource);
}
protected DocumentBuilderFactory createDocumentBuilderFactory(int validationMode, boolean namespaceAware)
throws ParserConfigurationException {
// 创建文档解析工厂
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(namespaceAware);
// 设置解析XML的校验
if (validationMode != XmlValidationModeDetector.VALIDATION_NONE) {
factory.setValidating(true);
if (validationMode == XmlValidationModeDetector.VALIDATION_XSD) {
// Enforce namespace aware for XSD...
factory.setNamespaceAware(true);
try {
factory.setAttribute(SCHEMA_LANGUAGE_ATTRIBUTE, XSD_SCHEMA_LANGUAGE);
}
catch (IllegalArgumentException ex) {
ParserConfigurationException pcex = new ParserConfigurationException(
"Unable to validate using XSD: Your JAXP provider [" + factory +
"] does not support XML Schema. Are you running on Java 1.4 with Apache Crimson? " +
"Upgrade to Apache Xerces (or Java 1.5) for full XSD support.");
pcex.initCause(ex);
throw pcex;
}
}
}
return factory;
}
上面的解析过程调用的是JAVAEE标准的JAXP标准进行处理。至此Spring IOC容器根据定位的Bean配置信息,将其加载读入并转换成为Document对象过程完成。
分配解析策略 XmlBeanDefinitionReader类中的doLoadBeanDefinition()方法是从特定XML文件中实际载入Bean配置资源的方法,该方法在载入Bean配置资源之后转换为Document对象,接下来调用registerBeanDefinitions()启动Spring IOC容器来对Bean定义的解析过程,registerBeanDefinitions()方法如下:
// 按照Spring 的Bean语义要求将Bean配置资源解析并转换为容器内部数据结构
public int registerBeanDefinitions(Document doc, Resource resource) throws BeanDefinitionStoreException {
// 得到BeanDefinitionDocumentReader来对xml格式的BeanDefinition解析
BeanDefinitionDocumentReader documentReader = createBeanDefinitionDocumentReader();
// 获取容器中注册的Bean数量
int countBefore = getRegistry().getBeanDefinitionCount();
// 解析过程入口,这里使用委派模式,BeanDefinitionDocumentReader只是个接口
// 具体的解析实现过程实现类DefaultBeanDefinitionDocumentReader完成
documentReader.registerBeanDefinitions(doc, createReaderContext(resource));
// 统计解析的Bean数量
return getRegistry().getBeanDefinitionCount() - countBefore;
}
Bean
配置资源的载入解析过程如下: 首先,通过调用XML
解析器将Bean
配置信息转换得到Document
对象,但是这些Document
对象并没有按照Spring
的Bean
规则进行解析,这一步是载入的过程。 其次,在完成通过的Xml解析之后,按照Spring Bean
的定义规则对Document
对象进行解析,其解析过程在接口BeanDefinitionDocumentReader
的实现类DefaultBeanDefinitionDocumentReader
中实现。
将配置载入内存 BeanDefinitionDocumentReader接口通过registerBeanDefinitions()方法调用其实现类DefaultBeanDefinitionDocumentReader对Document对象进行解析,解析代码如下:
// 根据Spring DTD对Bean的定义规则解析Bean定义Document对象
@Override
public void registerBeanDefinitions(Document doc, XmlReaderContext readerContext) {
// 获取Xml描述符
this.readerContext = readerContext;
logger.debug("Loading bean definitions");
// 获取Document的根元素
Element root = doc.getDocumentElement();
doRegisterBeanDefinitions(root);
}
protected void doRegisterBeanDefinitions(Element root) {
// Any nested <beans> elements will cause recursion in this method. In
// order to propagate and preserve <beans> default-* attributes correctly,
// keep track of the current (parent) delegate, which may be null. Create
// the new (child) delegate with a reference to the parent for fallback purposes,
// then ultimately reset this.delegate back to its original (parent) reference.
// this behavior emulates a stack of delegates without actually necessitating one.
// 具体的解析过程由BeanDefinitionParserDelegate实现,BeanDefinitionParserDelegate中定义了Spring Bean定义Xml文件的各种元素。
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)) {
if (logger.isInfoEnabled()) {
logger.info("Skipped XML bean definition file due to specified profiles [" + profileSpec +
"] not matching: " + getReaderContext().getResource());
}
return;
}
}
}
preProcessXml(root);
parseBeanDefinitions(root, this.delegate);
postProcessXml(root);
this.delegate = parent;
}
// 使用Spirng的Bean规则从Document的根元素开始进行Bean定义的Document对象
protected void parseBeanDefinitions(Element root, BeanDefinitionParserDelegate delegate) {
// Bean定义的Document对象使用了Spring默认的XML命名空间
if (delegate.isDefaultNamespace(root)) {
// 获取Bean定义的Document对象根元素的所有子节点
NodeList nl = root.getChildNodes();
for (int i = 0; i < nl.getLength(); i++) {
Node node = nl.item(i);
// 获取Document节点是XML元素节点
if (node instanceof Element) {
Element ele = (Element) node;
// Bean定义的Document的元素节点使用的是Spring默认的XML命名空间
if (delegate.isDefaultNamespace(ele)) {
// 使用SPring的Bean规则解析元素节点
parseDefaultElement(ele, delegate);
}
else {
// 没有使用Spring默认的XMl命名空间,则使用用户自定义的解析规则解析元素节点
delegate.parseCustomElement(ele);
}
}
}
}
else {
// Document的根节点没有使用Spring默认的命名空间,则使用用户自定义的解析规则解析Document根节点
delegate.parseCustomElement(root);
}
}
private void parseDefaultElement(Element ele, BeanDefinitionParserDelegate delegate) {
// 如果节点元素是<Import>导入元素,进行导入解析
if (delegate.nodeNameEquals(ele, IMPORT_ELEMENT)) {
importBeanDefinitionResource(ele);
}
// 如果元素是<Alias>别名元素,进行别名解析
else if (delegate.nodeNameEquals(ele, ALIAS_ELEMENT)) {
processAliasRegistration(ele);
}
// 元素节点既不是导入元素,也不是别名元素,即普通的<Bean>元素,按照Spring的Bean规则解析元素。
else if (delegate.nodeNameEquals(ele, BEAN_ELEMENT)) {
processBeanDefinition(ele, delegate);
}
else if (delegate.nodeNameEquals(ele, NESTED_BEANS_ELEMENT)) {
// recurse
doRegisterBeanDefinitions(ele);
}
}
// 解析<Import>导入元素,给定的导入路径加载Bean配置资源到Spring IOC容器中
protected void importBeanDefinitionResource(Element ele) {
// 获取给定的导入元素的location属性
String location = ele.getAttribute(RESOURCE_ATTRIBUTE);
// 如果导入元素的location属性为空,则没有导入任何资源,直接返回
if (!StringUtils.hasText(location)) {
getReaderContext().error("Resource location must not be empty", ele);
return;
}
// Resolve system properties: e.g. "${user.dir}"
// 使用系统变量值解析location属性值
location = getReaderContext().getEnvironment().resolveRequiredPlaceholders(location);
Set<Resource> actualResources = new LinkedHashSet<>(4);
// Discover whether the location is an absolute or relative URI
// 表示给定的导入元素的location是否为绝对路径
boolean absoluteLocation = false;
try {
absoluteLocation = ResourcePatternUtils.isUrl(location) || ResourceUtils.toURI(location).isAbsolute();
}
catch (URISyntaxException ex) {
// 给定的导入元素的location不是绝对路径
// cannot convert to an URI, considering the location relative
// unless it is the well-known Spring prefix "classpath*:"
}
// Absolute or relative?
// 给定的导入元素的location是绝对的
if (absoluteLocation) {
try {
// 使用资源读入器加载给定的路径Bean配置资源
int importCount = getReaderContext().getReader().loadBeanDefinitions(location, actualResources);
if (logger.isDebugEnabled()) {
logger.debug("Imported " + importCount + " bean definitions from URL location [" + location + "]");
}
}
catch (BeanDefinitionStoreException ex) {
getReaderContext().error(
"Failed to import bean definitions from URL location [" + location + "]", ele, ex);
}
}
else {
// No URL -> considering resource location as relative to the current file.
// 给定的导入元素的location是相对路径
try {
int importCount;
// 将给定导入元素的location封装为相对路径资源
Resource relativeResource = getReaderContext().getResource().createRelative(location);
// 封装的相对路径资源存在
if (relativeResource.exists()) {
// 使用资源读入器加载Bean配置资源
importCount = getReaderContext().getReader().loadBeanDefinitions(relativeResource);
actualResources.add(relativeResource);
}
else {
// 封装的相对路径资源不存在
// 获取SpringIOC容器资源读入器的基本路径
String baseLocation = getReaderContext().getResource().getURL().toString();
// 根据Spring IOC容器资源读入器的基本路径加载给定导入路径的资源
importCount = getReaderContext().getReader().loadBeanDefinitions(
StringUtils.applyRelativePath(baseLocation, location), actualResources);
}
if (logger.isDebugEnabled()) {
logger.debug("Imported " + importCount + " bean definitions from relative location [" + location + "]");
}
}
catch (IOException ex) {
getReaderContext().error("Failed to resolve current resource location", ele, ex);
}
catch (BeanDefinitionStoreException ex) {
getReaderContext().error("Failed to import bean definitions from relative location [" + location + "]",
ele, ex);
}
}
Resource[] actResArray = actualResources.toArray(new Resource[actualResources.size()]);
// 在解析完<Import> 元素之后,发送容器导入其他资源处理完成事件。
getReaderContext().fireImportProcessed(location, actResArray, extractSource(ele));
}
protected void processAliasRegistration(Element ele) {
// 获取<Alias>别名元素中name的属性值
String name = ele.getAttribute(NAME_ATTRIBUTE);
// 获取<Alias>别名元素中alias的属性值
String alias = ele.getAttribute(ALIAS_ATTRIBUTE);
boolean valid = true;
// <Alias>别名元素的name属性值为空
if (!StringUtils.hasText(name)) {
getReaderContext().error("Name must not be empty", ele);
valid = false;
}
// <Alias>别名元素的alias属性值为空
if (!StringUtils.hasText(alias)) {
getReaderContext().error("Alias must not be empty", ele);
valid = false;
}
if (valid) {
try {
// 向容器的资源读入器注册别名
getReaderContext().getRegistry().registerAlias(name, alias);
}
catch (Exception ex) {
getReaderContext().error("Failed to register alias '" + alias +
"' for bean with name '" + name + "'", ele, ex);
}
// 在解析完<Alias>元素之后,发送容器别名处理完成事件
getReaderContext().fireAliasRegistered(name, alias, extractSource(ele));
}
}
// 解析Bean配置资源Document对象的普通元素
protected void processBeanDefinition(Element ele, BeanDefinitionParserDelegate delegate) {
// BeanDefinitionHolder是对BeanDefinition的封装,即Bean定义的封装类,对Document对象中<Bean>元素的解析由BeanDefinitionParserDelegate实现
BeanDefinitionHolder bdHolder = delegate.parseBeanDefinitionElement(ele);
if (bdHolder != null) {
bdHolder = delegate.decorateBeanDefinitionIfRequired(ele, bdHolder);
try {
// Register the final decorated instance.
// 像Spring IOC容器注册解析得到的Bean定义,这是Bean定义向IOC容器注册的入口
BeanDefinitionReaderUtils.registerBeanDefinition(bdHolder, getReaderContext().getRegistry());
}
catch (BeanDefinitionStoreException ex) {
getReaderContext().error("Failed to register bean definition with name '" +
bdHolder.getBeanName() + "'", ele, ex);
}
// Send registration event.
// 在完成向Spring IOC容器注册解析得到的Bean定义之后,发送注册事件。
getReaderContext().fireComponentRegistered(new BeanComponentDefinition(bdHolder));
}
}
通过上面的源码可以看出Spring IOC容器对载入的Bean定义Document解析可以看出,我们在使用Spring时,在Spring配置文件中可以使用 元素来导入其他配置资源;使用 别名时,Spring IOC容器首先将别名元素定义的别名注册到容器中;对于既不是import也不是alias的元素,即Spring配置文件中普通的 元素,由BeanDefinitionParserDelegate类的parseBeanDefinitionElement()方法来实现。
载入<Bean>
元素 对Bean配置信息的解析由BeanDefinitionParserDelegate来解析,解析实现代码如下:
// 解析<Bean>元素的入口
@Nullable
public BeanDefinitionHolder parseBeanDefinitionElement(Element ele) {
return parseBeanDefinitionElement(ele, null);
}
/**
* Parses the supplied {@code <bean>} element. May return {@code null}
* if there were errors during parse. Errors are reported to the
* {@link org.springframework.beans.factory.parsing.ProblemReporter}.
*/
// 解析Bean配置信息中的<Bean>元素,这个方法中主要处理<bean>元素的id,name和别名属性
@Nullable
public BeanDefinitionHolder parseBeanDefinitionElement(Element ele, @Nullable BeanDefinition containingBean) {
// 获取<Bean>元素中的id属性值
String id = ele.getAttribute(ID_ATTRIBUTE);
// 获取<Bean>元素中的name属性值
String nameAttr = ele.getAttribute(NAME_ATTRIBUTE);
// 获取bean元素中的alias属性值
List<String> aliases = new ArrayList<>();
// 将bean元素中的所有name属性值存放到别名中
if (StringUtils.hasLength(nameAttr)) {
String[] nameArr = StringUtils.tokenizeToStringArray(nameAttr, MULTI_VALUE_ATTRIBUTE_DELIMITERS);
aliases.addAll(Arrays.asList(nameArr));
}
String beanName = id;
// 如果bean元素中没有配置id属性时,将别名中的第一个值赋值给beanName
if (!StringUtils.hasText(beanName) && !aliases.isEmpty()) {
beanName = aliases.remove(0);
if (logger.isDebugEnabled()) {
logger.debug("No XML 'id' specified - using '" + beanName +
"' as bean name and " + aliases + " as aliases");
}
}
// 检查bean元素所配置的id 或者name的唯一性,containingBean标识bean,元素中是否包含子bean元素
if (containingBean == null) {
// 检查bean元素所配置的id,name或者别名是否重复
checkNameUniqueness(beanName, aliases, ele);
}
// 详细对bean元素中配置的bean定义进行解析的地方
AbstractBeanDefinition beanDefinition = parseBeanDefinitionElement(ele, beanName, containingBean);
if (beanDefinition != null) {
if (!StringUtils.hasText(beanName)) {
try {
if (containingBean != null) {
// 如果bean元素中没有配置id,别名或者name,且没有包含子元素,bean元素,为解析的bean生成一个唯一beanName并注册
beanName = BeanDefinitionReaderUtils.generateBeanName(
beanDefinition, this.readerContext.getRegistry(), true);
}
else {
// 如果bean元素中没有配置id,别名或者name,且包含了子元素bean元素,为解析的bean使用别名想IOC容器中注册
beanName = this.readerContext.generateBeanName(beanDefinition);
// Register an alias for the plain bean class name, if still possible,
// if the generator returned the class name plus a suffix.
// This is expected for Spring 1.2/2.0 backwards compatibility.
// 为解析的bean使用别名注册时,为了向后兼容,Spring1.2/2.0,给别名添加类名后缀
String beanClassName = beanDefinition.getBeanClassName();
if (beanClassName != null &&
beanName.startsWith(beanClassName) && beanName.length() > beanClassName.length() &&
!this.readerContext.getRegistry().isBeanNameInUse(beanClassName)) {
aliases.add(beanClassName);
}
}
if (logger.isDebugEnabled()) {
logger.debug("Neither XML 'id' nor 'name' specified - " +
"using generated bean name [" + beanName + "]");
}
}
catch (Exception ex) {
error(ex.getMessage(), ele);
return null;
}
}
String[] aliasesArray = StringUtils.toStringArray(aliases);
return new BeanDefinitionHolder(beanDefinition, beanName, aliasesArray);
}
// 当解析出错时,返回null
return null;
}
/**
* Validate that the specified bean name and aliases have not been used already
* within the current level of beans element nesting.
*/
protected void checkNameUniqueness(String beanName, List<String> aliases, Element beanElement) {
String foundName = null;
if (StringUtils.hasText(beanName) && this.usedNames.contains(beanName)) {
foundName = beanName;
}
if (foundName == null) {
foundName = CollectionUtils.findFirstMatch(this.usedNames, aliases);
}
if (foundName != null) {
error("Bean name '" + foundName + "' is already used in this <beans> element", beanElement);
}
this.usedNames.add(beanName);
this.usedNames.addAll(aliases);
}
/**
* Parse the bean definition itself, without regard to name or aliases. May return
* {@code null} if problems occurred during the parsing of the bean definition.
*/
// 详细对<bean>元素中配置的Bean定义其他属性进行解析
// 由于上面的方法中已经对Bean的id,naem和别名属性进行了处理
// 该方法主要处理这三个以外的其他属性数据
@Nullable
public AbstractBeanDefinition parseBeanDefinitionElement(
Element ele, String beanName, @Nullable BeanDefinition containingBean) {
// 记录解析的bean元素
this.parseState.push(new BeanEntry(beanName));
// 这里只读取bean元素中配置的class名字,然后载入到BeanDefinition中去
// 只是记录配置的class名字,不做实例化,对象的实例化在依赖注入时完成
String className = null;
if (ele.hasAttribute(CLASS_ATTRIBUTE)) {
className = ele.getAttribute(CLASS_ATTRIBUTE).trim();
}
// 如果bean元素中配置了parent属性,则获取parent属性的值
String parent = null;
if (ele.hasAttribute(PARENT_ATTRIBUTE)) {
parent = ele.getAttribute(PARENT_ATTRIBUTE);
}
try {
// 根据bean元素配置的class名称和parent属性值创建BeanDefinition
// 为载入Bean定义信息做准备
AbstractBeanDefinition bd = createBeanDefinition(className, parent);
// 对当前的bean元素中配置的一些属性进行解析和设置,如配置的单态singleton属性等
parseBeanDefinitionAttributes(ele, beanName, containingBean, bd);
// 为bean元素解析的bean设置description信息
bd.setDescription(DomUtils.getChildElementValueByTagName(ele, DESCRIPTION_ELEMENT));
// 对bean元素的meta属性解析
parseMetaElements(ele, bd);
// 对bean元素的lookup-method属性解析
parseLookupOverrideSubElements(ele, bd.getMethodOverrides());
// 对bean元素的replaced-method属性解析
parseReplacedMethodSubElements(ele, bd.getMethodOverrides());
//解析bean元素的构造方法设置
parseConstructorArgElements(ele, bd);
// 解析bean元素的property设置
parsePropertyElements(ele, bd);
// 解析bean元素的qualifier属性
parseQualifierElements(ele, bd);
// 为当前解析的bean设置所需的资源和依赖对象
bd.setResource(this.readerContext.getResource());
bd.setSource(extractSource(ele));
return bd;
}
catch (ClassNotFoundException ex) {
error("Bean class [" + className + "] not found", ele, ex);
}
catch (NoClassDefFoundError err) {
error("Class that bean class [" + className + "] depends on not found", ele, err);
}
catch (Throwable ex) {
error("Unexpected failure during bean definition parsing", ele, ex);
}
finally {
this.parseState.pop();
}
// 解析异常返回null
return null;
}
Spring配置文件中bean元素中配置属性就是通过方法解析和设置到Bean中去的。这个过程只是创建了BeanDefinition信息,并没有创建和实例化Bean对象,在依赖注释时才使用这些信息创建和实例化具体的Bean对象。
载入<property>
元素 BeanDefinitionParserDelegate在解析 调用parsePropertyElements()方法解析 元素的 属性子元素,解析源码如下:
// 解析property元素
public void parsePropertyElement(Element ele, BeanDefinition bd) {
// 获取property元素的名字
String propertyName = ele.getAttribute(NAME_ATTRIBUTE);
if (!StringUtils.hasLength(propertyName)) {
error("Tag 'property' must have a 'name' attribute", ele);
return;
}
this.parseState.push(new PropertyEntry(propertyName));
try {
// 如果一个Bean中已经有同名的property存在,则不进行解析,直接返回。
// 即如果在同一个Bean中配置同名的property,则只有第一个起作用
if (bd.getPropertyValues().contains(propertyName)) {
error("Multiple 'property' definitions for property '" + propertyName + "'", ele);
return;
}
// 解析获取property的值
Object val = parsePropertyValue(ele, bd, propertyName);
// 根据property的名字和值创建property实例
PropertyValue pv = new PropertyValue(propertyName, val);
// 解析property元素中的属性
parseMetaElements(ele, pv);
pv.setSource(extractSource(ele));
bd.getPropertyValues().addPropertyValue(pv);
}
finally {
this.parseState.pop();
}
}
// 解析获取property值
@Nullable
public Object parsePropertyValue(Element ele, BeanDefinition bd, @Nullable String propertyName) {
String elementName = (propertyName != null) ?
"<property> element for property '" + propertyName + "'" :
"<constructor-arg> element";
// Should only have one child element: ref, value, list, etc.
// 获取property的所有子元素,只能是其中一种类型:ref,value,list,etc等
NodeList nl = ele.getChildNodes();
Element subElement = null;
for (int i = 0; i < nl.getLength(); i++) {
Node node = nl.item(i);
// 子元素不是description和meta属性
if (node instanceof Element && !nodeNameEquals(node, DESCRIPTION_ELEMENT) &&
!nodeNameEquals(node, META_ELEMENT)) {
// Child element is what we're looking for.
if (subElement != null) {
error(elementName + " must not contain more than one sub-element", ele);
}
else {
// 当前property元素包含子元素
subElement = (Element) node;
}
}
}
// 判断property的属性值是ref还是value,不允许即使ref又是value
boolean hasRefAttribute = ele.hasAttribute(REF_ATTRIBUTE);
boolean hasValueAttribute = ele.hasAttribute(VALUE_ATTRIBUTE);
if ((hasRefAttribute && hasValueAttribute) ||
((hasRefAttribute || hasValueAttribute) && subElement != null)) {
error(elementName +
" is only allowed to contain either 'ref' attribute OR 'value' attribute OR sub-element", ele);
}
// 如果属性值是ref,创建一个ref的数据对象runtimeBeanReference
// 这个对象封装了ref信息
if (hasRefAttribute) {
String refName = ele.getAttribute(REF_ATTRIBUTE);
if (!StringUtils.hasText(refName)) {
error(elementName + " contains empty 'ref' attribute", ele);
}
// 一个指向运行时所依赖对象的引用
RuntimeBeanReference ref = new RuntimeBeanReference(refName);
// 设置这个ref的数据对象是被当前的property对象所引用
ref.setSource(extractSource(ele));
return ref;
}
// 如果属性是value,创建一个value的数据对象typedStringValue
// 这个对象封装了value信息
else if (hasValueAttribute) {
// 一个持有string类型值的对象
TypedStringValue valueHolder = new TypedStringValue(ele.getAttribute(VALUE_ATTRIBUTE));
// 设置这个value数据对象是被当前的property对象所引用
valueHolder.setSource(extractSource(ele));
return valueHolder;
}
// 如果当前property元素还是子元素
else if (subElement != null) {
// 解析property的子元素
return parsePropertySubElement(subElement, bd);
}
else {
// property属性中既不是ref,也不是value属性,解析出错返回null
// Neither child element nor "ref" or "value" attribute found.
error(elementName + " must specify a ref or value", ele);
return null;
}
}
bean元素中的property元素的相关配置如何处理的:
ref被封装为指向依赖对象一个引用。
value配置都会封装成一个字符串类型的对象。
ref和value都通过“解析的数据类型属性值.setSource(extractSource(ele));”,方法将属性值/引用与所引用的属性关联起来。
载入<property>
的子元素 在BeanDefinitionParserDelegate类中parsePropertySubElement()方法对 中的子元素解析,源码如下:
// 解析property元素中ref,value或者集合等子元素
@Nullable
public Object parsePropertySubElement(Element ele, @Nullable BeanDefinition bd, @Nullable String defaultValueType) {
// 如果property没有使用spring默认的命名空间,则使用用户自定义的规则解析内嵌元素
if (!isDefaultNamespace(ele)) {
return parseNestedCustomElement(ele, bd);
}
// 如果子元素是bean,则使用解析bean元素的方法解析
else if (nodeNameEquals(ele, BEAN_ELEMENT)) {
BeanDefinitionHolder nestedBd = parseBeanDefinitionElement(ele, bd);
if (nestedBd != null) {
nestedBd = decorateBeanDefinitionIfRequired(ele, nestedBd, bd);
}
return nestedBd;
}
// 如果子元素是ref,ref中只能有以下3个属性:bean、local、parent
else if (nodeNameEquals(ele, REF_ELEMENT)) {
// 可以不再同一个Spring配置文件中,具体请参考spring对ref的配置规则
// A generic reference to any name of any bean.
String refName = ele.getAttribute(BEAN_REF_ATTRIBUTE);
boolean toParent = false;
if (!StringUtils.hasLength(refName)) {
// A reference to the id of another bean in a parent context.
// 获取property元素中parent属性值,引用父级容器中bean
refName = ele.getAttribute(PARENT_REF_ATTRIBUTE);
toParent = true;
if (!StringUtils.hasLength(refName)) {
error("'bean' or 'parent' is required for <ref> element", ele);
return null;
}
}
if (!StringUtils.hasText(refName)) {
error("<ref> element contains empty target attribute", ele);
return null;
}
// 创建ref类型数据,指向被引用的对象
RuntimeBeanReference ref = new RuntimeBeanReference(refName, toParent);
// 设置引用类型值是被当前子元素所引用
ref.setSource(extractSource(ele));
return ref;
}
// 如果子元素是idref,使用解析ref元素的方法解析
else if (nodeNameEquals(ele, IDREF_ELEMENT)) {
return parseIdRefElement(ele);
}
// 如果子元素为value,使用解析value元素的方法解析
else if (nodeNameEquals(ele, VALUE_ELEMENT)) {
return parseValueElement(ele, defaultValueType);
}
// 如果子元素是null,为property设置一个封装null值的字符串数据
else if (nodeNameEquals(ele, NULL_ELEMENT)) {
// It's a distinguished null value. Let's wrap it in a TypedStringValue
// object in order to preserve the source location.
TypedStringValue nullHolder = new TypedStringValue(null);
nullHolder.setSource(extractSource(ele));
return nullHolder;
}
// 如果子类是array,使用解析array集合子元素的方法解析
else if (nodeNameEquals(ele, ARRAY_ELEMENT)) {
return parseArrayElement(ele, bd);
}
// 如果子元素是list,使用解析list集合子元素的方法解析
else if (nodeNameEquals(ele, LIST_ELEMENT)) {
return parseListElement(ele, bd);
}
// 如果子元素为set,使用解析set集合子元素的方法解析
else if (nodeNameEquals(ele, SET_ELEMENT)) {
return parseSetElement(ele, bd);
}
// 如果子元素是map,使用解析map集合子元素的方法解析
else if (nodeNameEquals(ele, MAP_ELEMENT)) {
return parseMapElement(ele, bd);
}
// 如果子元素为props,使用解析props集合子元素的方法解析
else if (nodeNameEquals(ele, PROPS_ELEMENT)) {
return parsePropsElement(ele);
}
// 既不是ref,又不是value,也不是集合,则子元素配置错误,返回null
else {
error("Unknown property sub-element: [" + ele.getNodeName() + "]", ele);
return null;
}
}
通过上述源码分析,我们知道spring配置文件中,对property元素中配置的array、list、set、map、prop等各种集合子元素都通过上述方法解析,生成对应的数据对象,比如ManagedList、ManagedArray、ManagedSet等,这些Managed类是Spring对象BeanDefinition的数据封装,对集合数据类型的具体解析有各自的解析方法实现,解析方法的命名非常规范。
载入list的子元素 在BeanDefinitionParserDelegate类中的parseListElement()方法就是具体实现解析property元素中的list集合子元素,源码如下:
// 解析list集合子元素
public List<Object> parseListElement(Element collectionEle, @Nullable BeanDefinition bd) {
// 获取list元素中的value-type属性,即获取集合元素的数据类型。
String defaultElementType = collectionEle.getAttribute(VALUE_TYPE_ATTRIBUTE);
// 获取list集合元素中的所有子节点
NodeList nl = collectionEle.getChildNodes();
// spring中将list封装为ManagedList
ManagedList<Object> target = new ManagedList<>(nl.getLength());
target.setSource(extractSource(collectionEle));
// 设置集合目标数据类型
target.setElementTypeName(defaultElementType);
target.setMergeEnabled(parseMergeAttribute(collectionEle));
// 具体的list元素解析
parseCollectionElements(nl, target, bd, defaultElementType);
return target;
}
protected void parseCollectionElements(
NodeList elementNodes, Collection<Object> target, @Nullable BeanDefinition bd, String defaultElementType) {
// 遍历集合所有节点
for (int i = 0; i < elementNodes.getLength(); i++) {
Node node = elementNodes.item(i);
// 节点不是description节点
if (node instanceof Element && !nodeNameEquals(node, DESCRIPTION_ELEMENT)) {
// 将解析的元素加入集合中,递归调用下一个子元素
target.add(parsePropertySubElement((Element) node, bd, defaultElementType));
}
}
}
经过Spring Bean配置信息转换的Document对象中的元素层层解析Spring IOC现在已经将XML形式定一个Bean配置信息转换为Spring IOC所识别的数据结构-BeanDefinition,他是Bean配置信息中配置的POJO对象在Spring IOC容器中的映射,我们可以通过AbstractBeanDefinition为入口,看出了IOC容器进行索引、查询和操作。
通过Spring IOC对Bean配置资源的解析后,IOC容器大致完成了管理Bean对象的准备工作,即初始化过程,但是最为重要的依赖注入还没有发生,现在IOC容器中BeanDefinition存储的知识一些静态信息,接下来需要向容器注册Bean定义信息才能完全完成IOC容器的初始化过程。
分配注册策略 上面整个解析过程已经完成了,接下来我们分析DefaultBeanDefinitionDocumentReader对Bean定义转换的Document对象解析的流程中,在其parseDefaultElement()方法中完成对Document对象的解析后得到封装BeanDefinition的BeanDefinitionHold对象,然后调用BeanDefinitionReaderUtils的registerBeanDefinition()方法向IOC容器注册解析的Bean,BeanDefinitionReaderUtils的注册的源码如下:
public static void registerBeanDefinition(
BeanDefinitionHolder definitionHolder, BeanDefinitionRegistry registry)
throws BeanDefinitionStoreException {
// Register bean definition under primary name.
// 获取解析的BeanDefinition的名称
String beanName = definitionHolder.getBeanName();
// 向IOC容器注册BeanDefinition
registry.registerBeanDefinition(beanName, definitionHolder.getBeanDefinition());
// Register aliases for bean name, if any.
// 如果解析的BeanDefinition有别名,向容器注册别名
String[] aliases = definitionHolder.getAliases();
if (aliases != null) {
for (String alias : aliases) {
registry.registerAlias(beanName, alias);
}
}
}
当调用BeanDefinitionReaderUtils向IOC容器注册解析的BeanDefinition时,真正完成注册功能的DefaultListableBeanFactory。
向容器中注册 DefaultListableBeanFactory中使用一个HashMap的集合对象存放IOC容器中注册解析的BeanDefinition,向IOC容器注册的主要源码如下:
SimpleAliasRegistry
DefaultSingletonBeanRegistry
FactoryBeanRegistrySupport
AbstractBeanFactory
AbstractAutowireCapableBeanFactory
DefaultListableBeanFactory
// 存储注册信息的BeanDefinition
private final Map<String, BeanDefinition> beanDefinitionMap = new ConcurrentHashMap<>(256);
// 向IOC容器中注册解析的BeanDefinition
@Override
public void registerBeanDefinition(String beanName, BeanDefinition beanDefinition)
throws BeanDefinitionStoreException {
Assert.hasText(beanName, "Bean name must not be empty");
Assert.notNull(beanDefinition, "BeanDefinition must not be null");
// 校验解析的BeanDefinition
if (beanDefinition instanceof AbstractBeanDefinition) {
try {
((AbstractBeanDefinition) beanDefinition).validate();
}
catch (BeanDefinitionValidationException ex) {
throw new BeanDefinitionStoreException(beanDefinition.getResourceDescription(), beanName,
"Validation of bean definition failed", ex);
}
}
BeanDefinition oldBeanDefinition;
oldBeanDefinition = this.beanDefinitionMap.get(beanName);
if (oldBeanDefinition != null) {
if (!isAllowBeanDefinitionOverriding()) {
throw new BeanDefinitionStoreException(beanDefinition.getResourceDescription(), beanName,
"Cannot register bean definition [" + beanDefinition + "] for bean '" + beanName +
"': There is already [" + oldBeanDefinition + "] bound.");
}
else if (oldBeanDefinition.getRole() < beanDefinition.getRole()) {
// e.g. was ROLE_APPLICATION, now overriding with ROLE_SUPPORT or ROLE_INFRASTRUCTURE
if (this.logger.isWarnEnabled()) {
this.logger.warn("Overriding user-defined bean definition for bean '" + beanName +
"' with a framework-generated bean definition: replacing [" +
oldBeanDefinition + "] with [" + beanDefinition + "]");
}
}
else if (!beanDefinition.equals(oldBeanDefinition)) {
if (this.logger.isInfoEnabled()) {
this.logger.info("Overriding bean definition for bean '" + beanName +
"' with a different definition: replacing [" + oldBeanDefinition +
"] with [" + beanDefinition + "]");
}
}
else {
if (this.logger.isDebugEnabled()) {
this.logger.debug("Overriding bean definition for bean '" + beanName +
"' with an equivalent definition: replacing [" + oldBeanDefinition +
"] with [" + beanDefinition + "]");
}
}
this.beanDefinitionMap.put(beanName, beanDefinition);
}
else {
if (hasBeanCreationStarted()) {
// Cannot modify startup-time collection elements anymore (for stable iteration)
synchronized (this.beanDefinitionMap) {
this.beanDefinitionMap.put(beanName, beanDefinition);
List<String> updatedDefinitions = new ArrayList<>(this.beanDefinitionNames.size() + 1);
updatedDefinitions.addAll(this.beanDefinitionNames);
updatedDefinitions.add(beanName);
this.beanDefinitionNames = updatedDefinitions;
if (this.manualSingletonNames.contains(beanName)) {
Set<String> updatedSingletons = new LinkedHashSet<>(this.manualSingletonNames);
updatedSingletons.remove(beanName);
this.manualSingletonNames = updatedSingletons;
}
}
}
else {
// Still in startup registration phase
this.beanDefinitionMap.put(beanName, beanDefinition);
this.beanDefinitionNames.add(beanName);
this.manualSingletonNames.remove(beanName);
}
this.frozenBeanDefinitionNames = null;
}
// 检查是否有同名的BeanDefinition已经在IOC容器中注册
if (oldBeanDefinition != null || containsSingleton(beanName)) {
// 重置所有已经注册过的BeanDefinition的缓存
resetBeanDefinition(beanName);
}
}
Bean配置信息中配置的Bean被解析后,已经注册到IOC容器中,被容器管理起来,真正完成了IOC容器初始化所作的全部工作。现在IOC容器中已经建立了整个Bean的配置信息,这些BeanDefinition信息已经可以使用,并且可以被检索,IOC容器的作用就是对这些注册的Bean定义信息进行处理和维护。这些的注册的Bean定义信息是IOC容器控制反转的基础,正式有了这些注册的数据,容器才可以进行依赖注入。
基于Annotaion
的IOC初始化 从Spring2.0以后的版本中,Spring也引入了基于注解Annotation方式的配置,注册是JDK1.5中引入的一个新特性,用于简化Bean的配置,可以取代XML配置文件。开发人员对注解的态度也是罗卜白菜各有所爱,个人认为注解可以大大简化配置,提高开发速度,但也给后期维护增加难度。目前来说XML方式发展相对成熟,方便于统一管理。随着Spring Boot的兴起,基于注解的开发甚至出现了另配置。但作为个人的习惯而言,还是倾向于XML配置文件和注解相互的使用。Spring IOC容器对于类级别的注解和类内部的注解分以下两种处理策略:
类级别的注解:如@Component、@Repository、@Controller、@Servcie以及JavaEE6中的@ManagedBean和@Named注解,都是添加类上面的类级别注解,spring容器根据注解的过滤规则扫描读取注解Bean定义类,并将其注册到SPring IOC容器中
类内部的注解:如@Autowire、@Value、@Resource以及EJB和WebService相关的注解等,都是添加在类内部的字段或者方法上的类内部注解,SpringIOC容器通过Bean后置注解处理器解析Bean内部的注解。下面将根据这两种处理策略,分别分析Spring处理注解相关的源码。
定位Bean扫描路径 在Spring中管理注解Bean定义的容器有两个:AnnotationConfigApplicationContext和AnnotationConfigWebApplicationContext。这两个类是专门处理Spring注解方式为配置的容器,直接依赖注解作为容器配置信息来源的IOC容器。AnnotationConfigWebApplicationContext是AnnotationConfigApplicationContext的web版本,两者的用法以及对注解的处理方式几乎没有差别。现在我们以AnnotationConfigApplicationCntext为例看看它的源码:
public class AnnotationConfigApplicationContext extends GenericApplicationContext implements AnnotationConfigRegistry {
// 保存一个读取注册的Bean定义读取器,将其设置到容器中
private final AnnotatedBeanDefinitionReader reader;
// 保存一个扫描指定类路径中注册bean定义的扫描器,并将其设置到容器中
private final ClassPathBeanDefinitionScanner scanner;
/**
* Create a new AnnotationConfigApplicationContext that needs to be populated
* through {@link #register} calls and then manually {@linkplain #refresh refreshed}.
*/
// 默认构造函数,初始化一个空容器,容器不包含任何Bean信息,需要在稍后通过调用其register()
// 方法注册配置类,并调用refresh()方法刷新容器,出发容器对注解bean的载入、解析和注册过程。
public AnnotationConfigApplicationContext() {
this.reader = new AnnotatedBeanDefinitionReader(this);
this.scanner = new ClassPathBeanDefinitionScanner(this);
}
/**
* Create a new AnnotationConfigApplicationContext with the given DefaultListableBeanFactory.
* @param beanFactory the DefaultListableBeanFactory instance to use for this context
*/
public AnnotationConfigApplicationContext(DefaultListableBeanFactory beanFactory) {
super(beanFactory);
this.reader = new AnnotatedBeanDefinitionReader(this);
this.scanner = new ClassPathBeanDefinitionScanner(this);
}
/**
* Create a new AnnotationConfigApplicationContext, deriving bean definitions
* from the given annotated classes and automatically refreshing the context.
* @param annotatedClasses one or more annotated classes,
* e.g. {@link Configuration @Configuration} classes
*/
public AnnotationConfigApplicationContext(Class<?>... annotatedClasses) {
this();
register(annotatedClasses);
refresh();
}
/**
* Create a new AnnotationConfigApplicationContext, scanning for bean definitions
* in the given packages and automatically refreshing the context.
* @param basePackages the packages to check for annotated classes
*/
public AnnotationConfigApplicationContext(String... basePackages) {
this();
scan(basePackages);
refresh();
}
/**
* {@inheritDoc}
* <p>Delegates given environment to underlying {@link AnnotatedBeanDefinitionReader}
* and {@link ClassPathBeanDefinitionScanner} members.
*/
@Override
public void setEnvironment(ConfigurableEnvironment environment) {
super.setEnvironment(environment);
this.reader.setEnvironment(environment);
this.scanner.setEnvironment(environment);
}
/**
* Provide a custom {@link BeanNameGenerator} for use with {@link AnnotatedBeanDefinitionReader}
* and/or {@link ClassPathBeanDefinitionScanner}, if any.
* <p>Default is {@link org.springframework.context.annotation.AnnotationBeanNameGenerator}.
* <p>Any call to this method must occur prior to calls to {@link #register(Class...)}
* and/or {@link #scan(String...)}.
* @see AnnotatedBeanDefinitionReader#setBeanNameGenerator
* @see ClassPathBeanDefinitionScanner#setBeanNameGenerator
*/
// 为容器的注解bean读取器和bean扫描器设置bean名称产生器
public void setBeanNameGenerator(BeanNameGenerator beanNameGenerator) {
this.reader.setBeanNameGenerator(beanNameGenerator);
this.scanner.setBeanNameGenerator(beanNameGenerator);
getBeanFactory().registerSingleton(
AnnotationConfigUtils.CONFIGURATION_BEAN_NAME_GENERATOR, beanNameGenerator);
}
/**
* Set the {@link ScopeMetadataResolver} to use for detected bean classes.
* <p>The default is an {@link AnnotationScopeMetadataResolver}.
* <p>Any call to this method must occur prior to calls to {@link #register(Class...)}
* and/or {@link #scan(String...)}.
*/
// 为容器的注解bean读取器和注解bean扫描器设置作用范围元信息解析器
public void setScopeMetadataResolver(ScopeMetadataResolver scopeMetadataResolver) {
this.reader.setScopeMetadataResolver(scopeMetadataResolver);
this.scanner.setScopeMetadataResolver(scopeMetadataResolver);
}
//---------------------------------------------------------------------
// Implementation of AnnotationConfigRegistry
//---------------------------------------------------------------------
/**
* Register one or more annotated classes to be processed.
* <p>Note that {@link #refresh()} must be called in order for the context
* to fully process the new classes.
* @param annotatedClasses one or more annotated classes,
* e.g. {@link Configuration @Configuration} classes
* @see #scan(String...)
* @see #refresh()
*/
// 为容器注册一个被处理的注解bean,新注册的bean,必须手动调用容器的
// refresh()方法刷新容器,出发容器对新注册的bean的处理
public void register(Class<?>... annotatedClasses) {
Assert.notEmpty(annotatedClasses, "At least one annotated class must be specified");
this.reader.register(annotatedClasses);
}
/**
* Perform a scan within the specified base packages.
* <p>Note that {@link #refresh()} must be called in order for the context
* to fully process the new classes.
* @param basePackages the packages to check for annotated classes
* @see #register(Class...)
* @see #refresh()
*/
// 扫描制定包路径及其子包下面的注解类,为了使新添加的类被处理,必须手动调用
// refresh()方法刷新容器
public void scan(String... basePackages) {
Assert.notEmpty(basePackages, "At least one base package must be specified");
this.scanner.scan(basePackages);
}
...
}
通过上面源码的分析,我们可以看出Spring对注解的处理方式有两种:
直接将注解bean注册到容器中可以在初始化容器时注册;也可以在容器创建之后手动调用注册方法向容器注册,然后通过手动刷新容器,使容器对注册的注解bean进行处理。
通过扫描制定的包以及子包下面的所有类,在初始化注解容器时指定要扫描的路径,如果容器创建以后给定路径动态添加注解bean,则需要手动调用容器扫描的方法,然后手动刷新容器,使得容器对所注册的Bean进行处理。 下面我们来分析两种处理方式的实现过程。
### 读取Annotation
元数据 当创建注解处理容器时,如果传入的初始参数是具体的注解bean定义类时,注解容器读取并注册。
AnnotationConfigApplicationContext通过调用注解Bean定义读取器
AnnotateBeanDefinitionReader的register()方法向容器注册指定的注解bean,注解bean定义读取器向容器注册注解bean的源码如下:
<T> void doRegisterBean(Class<T> annotatedClass, @Nullable Supplier<T> instanceSupplier, @Nullable String name,
@Nullable Class<? extends Annotation>[] qualifiers, BeanDefinitionCustomizer... definitionCustomizers) {
// 根据指定的注解bean定义类,创建spring容器中对注解bean的封装的数据结构
AnnotatedGenericBeanDefinition abd = new AnnotatedGenericBeanDefinition(annotatedClass);
if (this.conditionEvaluator.shouldSkip(abd.getMetadata())) {
return;
}
abd.setInstanceSupplier(instanceSupplier);
// 解析注解bean定义的作用域,若@Scope("prototype"),则bean为原型类型:
// 若@Scope("singleton"),则bean为单态类型
ScopeMetadata scopeMetadata = this.scopeMetadataResolver.resolveScopeMetadata(abd);
// 为注解bean定义设置作用域
abd.setScope(scopeMetadata.getScopeName());
// 为注解bean定义生成bean名称
String beanName = (name != null ? name : this.beanNameGenerator.generateBeanName(abd, this.registry));
// 处理注解bean定义中的通用注解
AnnotationConfigUtils.processCommonDefinitionAnnotations(abd);
// 如果向容器注册注解bean定义时,使用额外的限定符注解,则解析限定符注解。
// 主要是配置的关于autowring自动依赖注入装配的限定条件,即@Qualifier注解
// spring自动依赖注入装配默认是按类型装配,如果使用@Qualifier则按名称
if (qualifiers != null) {
for (Class<? extends Annotation> qualifier : qualifiers) {
// 如果配置了@Primary注解,设置该bean为autowring自动依赖注入装配时的首选
if (Primary.class == qualifier) {
abd.setPrimary(true);
}
// 如果配置了@Lazy注解,则设置bean为非延迟初始化,如果没有配置
// 则该bean为预实例化
else if (Lazy.class == qualifier) {
abd.setLazyInit(true);
}
// 如果使用了除@Primary和@Lazy以外的其他注解,则为该bean添加一个
// autowring自动依赖注入装配限定符,该bean在进行autowring
// 自动依赖注入装配时,根据名称装配限定符指定的bean
else {
abd.addQualifier(new AutowireCandidateQualifier(qualifier));
}
}
}
for (BeanDefinitionCustomizer customizer : definitionCustomizers) {
customizer.customize(abd);
}
// 创建一个指定bean名称的bean定义对象,封装注解bean定义类数据
BeanDefinitionHolder definitionHolder = new BeanDefinitionHolder(abd, beanName);
// 根据注解bean定义类中配置的作用于,创建相应的代理对象
definitionHolder = AnnotationConfigUtils.applyScopedProxyMode(scopeMetadata, definitionHolder, this.registry);
// 向IOC容器注册注解bean类定义对象
BeanDefinitionReaderUtils.registerBeanDefinition(definitionHolder, this.registry);
}
从上面的源码我们可以看出,注册注解bean定义类的基本步骤:
需要使用注解元数据解析器解析注解bean中关于作用域的配置.
使用注解AnnotationConfigUtils的processCommonDefinitionAnnotations()方法处理注解bean定义类中通用的注解。
使用AnnotationConfigUtils的applyScopeProxyMode()方法创建对于作用域的代理对象。
通过BeanDefinitionReaderUtils向容器注册bean。
AnnotationScopeMetadataResolver解析作用于元数据 AnnotationScopeMetadataResolver通过resolveScopeMetadata()方法解析注解bean定义类的作用于远信息,即判断注册的bean是原生类型prototype还是单态singleton类型,其源码如下:
// 解析注解bean定义类中的作用域元信息
@Override
public ScopeMetadata resolveScopeMetadata(BeanDefinition definition) {
ScopeMetadata metadata = new ScopeMetadata();
if (definition instanceof AnnotatedBeanDefinition) {
AnnotatedBeanDefinition annDef = (AnnotatedBeanDefinition) definition;
// 从注解bean定义类的属性中查找属性为scope的值,及@Scope注解的值
// annDef.getMetadata().getAnnotationAttributes方法将bean
// 中所有的注解和注解的值存放在一个map集合中
AnnotationAttributes attributes = AnnotationConfigUtils.attributesFor(
annDef.getMetadata(), this.scopeAnnotationType);
// 将获取到的@Scope注解的值设置到要返回的对象中
if (attributes != null) {
metadata.setScopeName(attributes.getString("value"));
// 获取@Scope注解中的proxyMode属性值,在创建代理对象时会用到
ScopedProxyMode proxyMode = attributes.getEnum("proxyMode");
// 如果@Scope的proxyMode属性为DEFAULT或者NO
if (proxyMode == ScopedProxyMode.DEFAULT) {
// 设置proxyMode为NO
proxyMode = this.defaultProxyMode;
}
// 为返回的元数据设置proxyMode
metadata.setScopedProxyMode(proxyMode);
}
}
// 返回解析的作用域元信息对象
return metadata;
}
上述代码中的annDef.getMetadata().getAnnotationAttributes()方法就是获取对象中指定类型的注解的值。
annotationConfigUtils处理注解Bean定义类中的通用注解 AnnotationConfigUtils类的processCommonDefinitionAnnotations()向容器注册bean之前,首先对注解bean定义类中的通用Spring注解进行处理,源码如下:
// 处理bean定义中通用注解
static void processCommonDefinitionAnnotations(AnnotatedBeanDefinition abd, AnnotatedTypeMetadata metadata) {
AnnotationAttributes lazy = attributesFor(metadata, Lazy.class);
// 如果bean定义中有@Lazy注解,则将该bean预实例化属性设置为@Lazy注解的值
if (lazy != null) {
abd.setLazyInit(lazy.getBoolean("value"));
}
else if (abd.getMetadata() != metadata) {
lazy = attributesFor(abd.getMetadata(), Lazy.class);
if (lazy != null) {
abd.setLazyInit(lazy.getBoolean("value"));
}
}
// 如果Bean定义有@Primary注解,则为该Bean设置为autowiring自动依赖注入装配的首选对象
if (metadata.isAnnotated(Primary.class.getName())) {
abd.setPrimary(true);
}
// 如果Bean定义中有@DependsOn注解,则为该Bean设置所依赖的Bean名称
// 容器将确保在实例化该Bean之前首先实例化所依赖的Bean
AnnotationAttributes dependsOn = attributesFor(metadata, DependsOn.class);
if (dependsOn != null) {
abd.setDependsOn(dependsOn.getStringArray("value"));
}
if (abd instanceof AbstractBeanDefinition) {
AbstractBeanDefinition absBd = (AbstractBeanDefinition) abd;
AnnotationAttributes role = attributesFor(metadata, Role.class);
if (role != null) {
absBd.setRole(role.getNumber("value").intValue());
}
AnnotationAttributes description = attributesFor(metadata, Description.class);
if (description != null) {
absBd.setDescription(description.getString("value"));
}
}
}
AnnotationConfigUtils根据注解bean定义类中配置的作用域为其应用相应的代理策略 AnnotationConfigUtils类的applyScopeProxyMode()方法根据注解Bean定义类中配置的作用于@Scope注解的值,为bean定义应用相应的代理模式,主要是在Spring面向切面变成aop中使用。源码如下:
// 根据作用于为bean应用引用的代码模式
static BeanDefinitionHolder applyScopedProxyMode(
ScopeMetadata metadata, BeanDefinitionHolder definition, BeanDefinitionRegistry registry) {
// 获取注解bean定义类中@Scope注解的proxyMode属性值
ScopedProxyMode scopedProxyMode = metadata.getScopedProxyMode();
// 如果配置的@Scope注解的proxyMode属性值为NO,则不应用代理模式
if (scopedProxyMode.equals(ScopedProxyMode.NO)) {
return definition;
}
// 获取配置的@Scope注解的proxyMode属性值,如果为TARGET_CLASS
// 则返回true,如果为INTERFACES,则返回false
boolean proxyTargetClass = scopedProxyMode.equals(ScopedProxyMode.TARGET_CLASS);
// 为注册的Bean创建相应的代理对象
return ScopedProxyCreator.createScopedProxy(definition, registry, proxyTargetClass);
}
BeanDefinitionReaderUtils向容器注册Bean BeanDefinitionReaderUtils主要是校验BeanDefinition信息,然后将Bean添加到容器中一个管理BeanDefinition的HashMap中。
扫描指定包并解析为BeanDefinition 当创建注解处理容器时,如果传入的初始参数是注解Bean定义类所在的包时,注解容器将扫描给定的包及子包,将扫描到的注解bean定义载入并注册。
ClassPathBeanDefinitionScanner扫描给定的包及其子包
AnnotationConfigApplicationContext通过调用类路径Bean定义扫描器ClassPathBeanDefinitionScanner扫描给定包及其子包下的所有类,主要源码如下:
public class ClassPathBeanDefinitionScanner extends ClassPathScanningCandidateComponentProvider {
private final BeanDefinitionRegistry registry;
private BeanDefinitionDefaults beanDefinitionDefaults = new BeanDefinitionDefaults();
@Nullable
private String[] autowireCandidatePatterns;
private BeanNameGenerator beanNameGenerator = new AnnotationBeanNameGenerator();
private ScopeMetadataResolver scopeMetadataResolver = new AnnotationScopeMetadataResolver();
private boolean includeAnnotationConfig = true;
/**
* Create a new {@code ClassPathBeanDefinitionScanner} for the given bean factory.
* @param registry the {@code BeanFactory} to load bean definitions into, in the form
* of a {@code BeanDefinitionRegistry}
*/
// 创建一个类路径bean定义扫描器
public ClassPathBeanDefinitionScanner(BeanDefinitionRegistry registry) {
this(registry, true);
}
/**
* Create a new {@code ClassPathBeanDefinitionScanner} for the given bean factory.
* <p>If the passed-in bean factory does not only implement the
* {@code BeanDefinitionRegistry} interface but also the {@code ResourceLoader}
* interface, it will be used as default {@code ResourceLoader} as well. This will
* usually be the case for {@link org.springframework.context.ApplicationContext}
* implementations.
* <p>If given a plain {@code BeanDefinitionRegistry}, the default {@code ResourceLoader}
* will be a {@link org.springframework.core.io.support.PathMatchingResourcePatternResolver}.
* <p>If the passed-in bean factory also implements {@link EnvironmentCapable} its
* environment will be used by this reader. Otherwise, the reader will initialize and
* use a {@link org.springframework.core.env.StandardEnvironment}. All
* {@code ApplicationContext} implementations are {@code EnvironmentCapable}, while
* normal {@code BeanFactory} implementations are not.
* @param registry the {@code BeanFactory} to load bean definitions into, in the form
* of a {@code BeanDefinitionRegistry}
* @param useDefaultFilters whether to include the default filters for the
* {@link org.springframework.stereotype.Component @Component},
* {@link org.springframework.stereotype.Repository @Repository},
* {@link org.springframework.stereotype.Service @Service}, and
* {@link org.springframework.stereotype.Controller @Controller} stereotype annotations
* @see #setResourceLoader
* @see #setEnvironment
*/
// 为容器创建一个类bean定义扫描器,定指定是否使用默认的扫描过滤规则
// 即spring默认扫描配置:@Component、@Repository、@Service、@Controller
// 注解的bean,同时支持javaee6的@ManagedBean和JSR-330的@Named注解
public ClassPathBeanDefinitionScanner(BeanDefinitionRegistry registry, boolean useDefaultFilters) {
this(registry, useDefaultFilters, getOrCreateEnvironment(registry));
}
/**
* Create a new {@code ClassPathBeanDefinitionScanner} for the given bean factory and
* using the given {@link Environment} when evaluating bean definition profile metadata.
* <p>If the passed-in bean factory does not only implement the {@code
* BeanDefinitionRegistry} interface but also the {@link ResourceLoader} interface, it
* will be used as default {@code ResourceLoader} as well. This will usually be the
* case for {@link org.springframework.context.ApplicationContext} implementations.
* <p>If given a plain {@code BeanDefinitionRegistry}, the default {@code ResourceLoader}
* will be a {@link org.springframework.core.io.support.PathMatchingResourcePatternResolver}.
* @param registry the {@code BeanFactory} to load bean definitions into, in the form
* of a {@code BeanDefinitionRegistry}
* @param useDefaultFilters whether to include the default filters for the
* {@link org.springframework.stereotype.Component @Component},
* {@link org.springframework.stereotype.Repository @Repository},
* {@link org.springframework.stereotype.Service @Service}, and
* {@link org.springframework.stereotype.Controller @Controller} stereotype annotations
* @param environment the Spring {@link Environment} to use when evaluating bean
* definition profile metadata
* @since 3.1
* @see #setResourceLoader
*/
public ClassPathBeanDefinitionScanner(BeanDefinitionRegistry registry, boolean useDefaultFilters,
Environment environment) {
this(registry, useDefaultFilters, environment,
(registry instanceof ResourceLoader ? (ResourceLoader) registry : null));
}
/**
* Create a new {@code ClassPathBeanDefinitionScanner} for the given bean factory and
* using the given {@link Environment} when evaluating bean definition profile metadata.
* @param registry the {@code BeanFactory} to load bean definitions into, in the form
* of a {@code BeanDefinitionRegistry}
* @param useDefaultFilters whether to include the default filters for the
* {@link org.springframework.stereotype.Component @Component},
* {@link org.springframework.stereotype.Repository @Repository},
* {@link org.springframework.stereotype.Service @Service}, and
* {@link org.springframework.stereotype.Controller @Controller} stereotype annotations
* @param environment the Spring {@link Environment} to use when evaluating bean
* definition profile metadata
* @param resourceLoader the {@link ResourceLoader} to use
* @since 4.3.6
*/
public ClassPathBeanDefinitionScanner(BeanDefinitionRegistry registry, boolean useDefaultFilters,
Environment environment, @Nullable ResourceLoader resourceLoader) {
Assert.notNull(registry, "BeanDefinitionRegistry must not be null");
// 为容器设置加载bean定义的注解器
this.registry = registry;
if (useDefaultFilters) {
registerDefaultFilters();
}
setEnvironment(environment);
// 为容器设置资源加载器
setResourceLoader(resourceLoader);
}
/**
* Return the BeanDefinitionRegistry that this scanner operates on.
*/
@Override
public final BeanDefinitionRegistry getRegistry() {
return this.registry;
}
/**
* Set the defaults to use for detected beans.
* @see BeanDefinitionDefaults
*/
public void setBeanDefinitionDefaults(@Nullable BeanDefinitionDefaults beanDefinitionDefaults) {
this.beanDefinitionDefaults =
(beanDefinitionDefaults != null ? beanDefinitionDefaults : new BeanDefinitionDefaults());
}
/**
* Return the defaults to use for detected beans (never {@code null}).
* @since 4.1
*/
public BeanDefinitionDefaults getBeanDefinitionDefaults() {
return this.beanDefinitionDefaults;
}
/**
* Set the name-matching patterns for determining autowire candidates.
* @param autowireCandidatePatterns the patterns to match against
*/
public void setAutowireCandidatePatterns(@Nullable String... autowireCandidatePatterns) {
this.autowireCandidatePatterns = autowireCandidatePatterns;
}
/**
* Set the BeanNameGenerator to use for detected bean classes.
* <p>Default is a {@link AnnotationBeanNameGenerator}.
*/
public void setBeanNameGenerator(@Nullable BeanNameGenerator beanNameGenerator) {
this.beanNameGenerator = (beanNameGenerator != null ? beanNameGenerator : new AnnotationBeanNameGenerator());
}
/**
* Set the ScopeMetadataResolver to use for detected bean classes.
* Note that this will override any custom "scopedProxyMode" setting.
* <p>The default is an {@link AnnotationScopeMetadataResolver}.
* @see #setScopedProxyMode
*/
public void setScopeMetadataResolver(@Nullable ScopeMetadataResolver scopeMetadataResolver) {
this.scopeMetadataResolver =
(scopeMetadataResolver != null ? scopeMetadataResolver : new AnnotationScopeMetadataResolver());
}
/**
* Specify the proxy behavior for non-singleton scoped beans.
* Note that this will override any custom "scopeMetadataResolver" setting.
* <p>The default is {@link ScopedProxyMode#NO}.
* @see #setScopeMetadataResolver
*/
public void setScopedProxyMode(ScopedProxyMode scopedProxyMode) {
this.scopeMetadataResolver = new AnnotationScopeMetadataResolver(scopedProxyMode);
}
/**
* Specify whether to register annotation config post-processors.
* <p>The default is to register the post-processors. Turn this off
* to be able to ignore the annotations or to process them differently.
*/
public void setIncludeAnnotationConfig(boolean includeAnnotationConfig) {
this.includeAnnotationConfig = includeAnnotationConfig;
}
/**
* Perform a scan within the specified base packages.
* @param basePackages the packages to check for annotated classes
* @return number of beans registered
*/
public int scan(String... basePackages) {
// 获取容器中已经注册的Bean个数
int beanCountAtScanStart = this.registry.getBeanDefinitionCount();
// 启动扫描器扫描给定包
doScan(basePackages);
// Register annotation config processors, if necessary.
// 注册注解配置Annotation config处理器
if (this.includeAnnotationConfig) {
AnnotationConfigUtils.registerAnnotationConfigProcessors(this.registry);
}
// 返回注册的bean个数
return (this.registry.getBeanDefinitionCount() - beanCountAtScanStart);
}
/**
* Perform a scan within the specified base packages,
* returning the registered bean definitions.
* <p>This method does <i>not</i> register an annotation config processor
* but rather leaves this up to the caller.
* @param basePackages the packages to check for annotated classes
* @return set of beans registered if any for tooling registration purposes (never {@code null})
*/
// 类路径bean定义扫描器扫描给定包及其子包
protected Set<BeanDefinitionHolder> doScan(String... basePackages) {
Assert.notEmpty(basePackages, "At least one base package must be specified");
// 创建一个集合,存放扫描到bean定义的封装类
Set<BeanDefinitionHolder> beanDefinitions = new LinkedHashSet<>();
// 遍历扫描所有给定的包
for (String basePackage : basePackages) {
// 调用父类classPathScanningCandidateComponentProvider的方法
// 扫描给定类路径,获取符合条件的bean定义
Set<BeanDefinition> candidates = findCandidateComponents(basePackage);
// 便利扫描到的bean
for (BeanDefinition candidate : candidates) {
// 获取bean定义类中@Scope注解的值,即获取bean的作用域
ScopeMetadata scopeMetadata = this.scopeMetadataResolver.resolveScopeMetadata(candidate);
// 为bean设置注解配置的作用于
candidate.setScope(scopeMetadata.getScopeName());
// 为bean生成名称
String beanName = this.beanNameGenerator.generateBeanName(candidate, this.registry);
// 如果扫描到的bean不是spring的注解bean,则为bean的默认值
// 设置bean的自动依赖注入装配属性等
if (candidate instanceof AbstractBeanDefinition) {
postProcessBeanDefinition((AbstractBeanDefinition) candidate, beanName);
}
// 如果扫描到的bean是spring的注解bean,则处理其通用的spring注解
if (candidate instanceof AnnotatedBeanDefinition) {
// 处理注解bean中通用的注解,在分析注解bean定义类读取器时已经分析过
AnnotationConfigUtils.processCommonDefinitionAnnotations((AnnotatedBeanDefinition) candidate);
}
// 根据bean名称检查指定的bean是否需要在容器中注册,或者在容器中冲突
if (checkCandidate(beanName, candidate)) {
BeanDefinitionHolder definitionHolder = new BeanDefinitionHolder(candidate, beanName);
// 根据注解中的配置的作用域,为bean应用相应的代理模式
definitionHolder =
AnnotationConfigUtils.applyScopedProxyMode(scopeMetadata, definitionHolder, this.registry);
beanDefinitions.add(definitionHolder);
// 向容器注册扫描到的bean
registerBeanDefinition(definitionHolder, this.registry);
}
}
}
return beanDefinitions;
}
类路径bean定义扫描器ClassPathBeanDefinitionScanner主要通过findCandidateComponents()方法调用其父类ClassPathScanningCandidateComponentProvider类来扫描获取给定包及其子包下的类。 2) ClassPathScanningCandidateComponentProvider类的findCandidateComponents()方法具体实现扫描给定类路径包的功能,主要源码如下下:
// 保存过滤规则要包含的注解,即Spring默认的@Component、@Repository、@Service、
// @Controller注解的Bean,以及JavaEE6的@ManagedBean和JSR-330的@Named注解
private final List<TypeFilter> includeFilters = new LinkedList<>();
// 保存过滤规则要排除的注解
private final List<TypeFilter> excludeFilters = new LinkedList<>();
// 构造方法,该方法在子类ClassPathBeanDefinitionScanner的构造方法被调用
public ClassPathScanningCandidateComponentProvider(boolean useDefaultFilters) {
this(useDefaultFilters, new StandardEnvironment());
}
// 向容器注册过滤规则
@SuppressWarnings("unchecked")
protected void registerDefaultFilters() {
// 向要包含的归路规则中添加@Component注解类,注意Spring中@Repository、@Service
// 和Controller都是Component,因为这些注解都添加了@Component注解
this.includeFilters.add(new AnnotationTypeFilter(Component.class));
// 获取当前类的类加载器
ClassLoader cl = ClassPathScanningCandidateComponentProvider.class.getClassLoader();
try {
// 向要包含的过滤规则中添加javaee6的@ManagedBean注解
this.includeFilters.add(new AnnotationTypeFilter(
((Class<? extends Annotation>) ClassUtils.forName("javax.annotation.ManagedBean", cl)), false));
logger.debug("JSR-250 'javax.annotation.ManagedBean' found and supported for component scanning");
}
catch (ClassNotFoundException ex) {
// JSR-250 1.1 API (as included in Java EE 6) not available - simply skip.
}
try {
// 向要包含的过滤规则添加@Named注解
this.includeFilters.add(new AnnotationTypeFilter(
((Class<? extends Annotation>) ClassUtils.forName("javax.inject.Named", cl)), false));
logger.debug("JSR-330 'javax.inject.Named' annotation found and supported for component scanning");
}
catch (ClassNotFoundException ex) {
// JSR-330 API not available - simply skip.
}
}
// 扫描给定类路径的包
public Set<BeanDefinition> findCandidateComponents(String basePackage) {
if (this.componentsIndex != null && indexSupportsIncludeFilters()) {
return addCandidateComponentsFromIndex(this.componentsIndex, basePackage);
}
else {
return scanCandidateComponents(basePackage);
}
}
private Set<BeanDefinition> addCandidateComponentsFromIndex(CandidateComponentsIndex index, String basePackage) {
// 创建存储扫描到的类的集合
Set<BeanDefinition> candidates = new LinkedHashSet<>();
try {
Set<String> types = new HashSet<>();
for (TypeFilter filter : this.includeFilters) {
String stereotype = extractStereotype(filter);
if (stereotype == null) {
throw new IllegalArgumentException("Failed to extract stereotype from "+ filter);
}
types.addAll(index.getCandidateTypes(basePackage, stereotype));
}
boolean traceEnabled = logger.isTraceEnabled();
boolean debugEnabled = logger.isDebugEnabled();
for (String type : types) {
// 为指定资源获取元数据读取器,元信息读取器通过汇编ASM读取资源远信息
MetadataReader metadataReader = getMetadataReaderFactory().getMetadataReader(type);
// 如果扫描的类符合容器配置的过滤规则
if (isCandidateComponent(metadataReader)) {
// 通过汇编ASM读取资源字节码中的bean定义元信息
AnnotatedGenericBeanDefinition sbd = new AnnotatedGenericBeanDefinition(
metadataReader.getAnnotationMetadata());
if (isCandidateComponent(sbd)) {
if (debugEnabled) {
logger.debug("Using candidate component class from index: " + type);
}
candidates.add(sbd);
}
else {
if (debugEnabled) {
logger.debug("Ignored because not a concrete top-level class: " + type);
}
}
}
else {
if (traceEnabled) {
logger.trace("Ignored because matching an exclude filter: " + type);
}
}
}
}
catch (IOException ex) {
throw new BeanDefinitionStoreException("I/O failure during classpath scanning", ex);
}
return candidates;
}
// 判断元信息读取器读取的类是否符合容器定义的注解过滤规则
protected boolean isCandidateComponent(MetadataReader metadataReader) throws IOException {
// 如果读取的类的注解在排除注解过滤规则中,返回false
for (TypeFilter tf : this.excludeFilters) {
if (tf.match(metadataReader, getMetadataReaderFactory())) {
return false;
}
}
// 如果读取的类的注解在包含的注解的过滤规则中,则返回true
for (TypeFilter tf : this.includeFilters) {
if (tf.match(metadataReader, getMetadataReaderFactory())) {
return isConditionMatch(metadataReader);
}
}
// 如果读取的类的注解即不再排除规则,也不再包含规则,则返回false。
return false;
}