Spring源码入门——AnnotationBeanNameGenerator解析
---恢复内容开始---
接上篇,上篇解析了DefaultBeanGenerator生成bean name的过程(http://www.cnblogs.com/jason0529/p/5272265.html ), 本篇我们继续解析另一类bean name生成方式。
spring定义bean有两种模式,配置文件(xml,properties)和注解。注:jpa的声明接口生成bean应该可以算第三种模式,这里不讨论。
对两种bean定义方式,spring提供了两种不同的bean name实现方式去实现不同的模式。AnnotationBeanNameGenerator能够处理 Component,Respository,Service,Controller这四个常用的注解,解析为bean name注给他们对应的value属性。另外jee的javax.annotation.ManagedBean和javax.inject.Named也可以支持。
当Component,Respository,Service,Controller注解的value树形没有自定义时,会根据类的名称生成一个短的bean name。例如: com.xyz.FooServiceImpl -> fooServiceImpl
入口肯定是BeanNameGenerator接口声明的generateBeanName(BeanDefinition, BeanDefinitionRegistry) 方法,该方法做了一个分类判断,处理AnnotationBeanDefinition和default两种方式的。
public String generateBeanName(BeanDefinition definition, BeanDefinitionRegistry registry) {
//判断是否是否是AnnotatedBeanDefinition的子类, AnnotatedBeanDefinition是BeanDefinition的一个子类
//如果是AnnotatedBeanDefinition , 按照注解生成模式生成信息,否则生成默认的bean name
if (definition instanceof AnnotatedBeanDefinition) {
String beanName = determineBeanNameFromAnnotation((AnnotatedBeanDefinition) definition);
//保证生成的bean name 非空
if (StringUtils.hasText(beanName)) {
// Explicit bean name found.
return beanName;
}
}
// Fallback: generate a unique default bean name.
return buildDefaultBeanName(definition, registry);
}
先从相对简单的default看起,这段代码的疑点是生成的bean name并没有和DefaultBeanNameGenerator一样做唯一性校验,可能导致不同包下面存在相同的类名时,会产生两个name一样的bean,引发spring 异常。
/**
* Derive a default bean name from the given bean definition.
* <p>The default implementation delegates to {@link #buildDefaultBeanName(BeanDefinition)}.
* @param definition the bean definition to build a bean name for
* @param registry the registry that the given bean definition is being registered with
* @return the default bean name (never {@code null})
*/
protected String buildDefaultBeanName(BeanDefinition definition, BeanDefinitionRegistry registry) {
//没有做 name 唯一性校验。
return buildDefaultBeanName(definition);
} /**
* Derive a default bean name from the given bean definition.
* <p>The default implementation simply builds a decapitalized version
* of the short class name: e.g. "mypackage.MyJdbcDao" -> "myJdbcDao".
* <p>Note that inner classes will thus have names of the form
* "outerClassName.innerClassName", which because of the period in the
* name may be an issue if you are autowiring by name.
* @param definition the bean definition to build a bean name for
* @return the default bean name (never {@code null})
*/
protected String buildDefaultBeanName(BeanDefinition definition) {
//具体类名获取和格式化先不做具体讨论
String shortClassName = ClassUtils.getShortName(definition.getBeanClassName());
return Introspector.decapitalize(shortClassName);
}
---恢复内容结束---
接上篇,上篇解析了DefaultBeanGenerator生成bean name的过程(http://www.cnblogs.com/jason0529/p/5272265.html ), 本篇我们继续解析另一类bean name生成方式。
spring定义bean有两种模式,配置文件(xml,properties)和注解。注:jpa的声明接口生成bean应该可以算第三种模式,这里不讨论。
对两种bean定义方式,spring提供了两种不同的bean name实现方式去实现不同的模式。AnnotationBeanNameGenerator能够处理 Component,Respository,Service,Controller这四个常用的注解,解析为bean name注给他们对应的value属性。另外jee的javax.annotation.ManagedBean和javax.inject.Named也可以支持。
当Component,Respository,Service,Controller注解的value树形没有自定义时,会根据类的名称生成一个短的bean name。例如: com.xyz.FooServiceImpl -> fooServiceImpl
入口肯定是BeanNameGenerator接口声明的generateBeanName(BeanDefinition, BeanDefinitionRegistry) 方法,该方法做了一个分类判断,处理AnnotationBeanDefinition和default两种方式的。
public String generateBeanName(BeanDefinition definition, BeanDefinitionRegistry registry) {
//判断是否是否是AnnotatedBeanDefinition的子类, AnnotatedBeanDefinition是BeanDefinition的一个子类
//如果是AnnotatedBeanDefinition , 按照注解生成模式生成信息,否则生成默认的bean name
if (definition instanceof AnnotatedBeanDefinition) {
String beanName = determineBeanNameFromAnnotation((AnnotatedBeanDefinition) definition);
//保证生成的bean name 非空
if (StringUtils.hasText(beanName)) {
// Explicit bean name found.
return beanName;
}
}
// Fallback: generate a unique default bean name.
return buildDefaultBeanName(definition, registry);
}
先从相对简单的default看起,这段代码的疑点是生成的bean name并没有和DefaultBeanNameGenerator一样做唯一性校验,可能导致不同包下面存在相同的类名时,会产生两个name一样的bean,引发spring 异常。
/**
* Derive a default bean name from the given bean definition.
* <p>The default implementation delegates to {@link #buildDefaultBeanName(BeanDefinition)}.
* @param definition the bean definition to build a bean name for
* @param registry the registry that the given bean definition is being registered with
* @return the default bean name (never {@code null})
*/
protected String buildDefaultBeanName(BeanDefinition definition, BeanDefinitionRegistry registry) {
//没有做 name 唯一性校验。
return buildDefaultBeanName(definition);
} /**
* Derive a default bean name from the given bean definition.
* <p>The default implementation simply builds a decapitalized version
* of the short class name: e.g. "mypackage.MyJdbcDao" -> "myJdbcDao".
* <p>Note that inner classes will thus have names of the form
* "outerClassName.innerClassName", which because of the period in the
* name may be an issue if you are autowiring by name.
* @param definition the bean definition to build a bean name for
* @return the default bean name (never {@code null})
*/
protected String buildDefaultBeanName(BeanDefinition definition) {
//具体类名获取和格式化先不做具体讨论
String shortClassName = ClassUtils.getShortName(definition.getBeanClassName());
return Introspector.decapitalize(shortClassName);
}
其实ClassUtils.getShortName也很简单,根据传入字符串获取一个具体类名称,不含包路径,考虑cglib代理的类,做了一个特殊处理。
/**
* Get the class name without the qualified package name.
* @param className the className to get the short name for
* @return the class name of the class without the package name
* @throws IllegalArgumentException if the className is empty
*/
public static String getShortName(String className) {
Assert.hasLength(className, "Class name must not be empty");
int lastDotIndex = className.lastIndexOf(PACKAGE_SEPARATOR);
int nameEndIndex = className.indexOf(CGLIB_CLASS_SEPARATOR);
if (nameEndIndex == -1) {
nameEndIndex = className.length();
}
String shortName = className.substring(lastDotIndex + 1, nameEndIndex);
shortName = shortName.replace(INNER_CLASS_SEPARATOR, PACKAGE_SEPARATOR);
return shortName;
}
接下来看第二条线,AnnotationBeanDefinition的beanName如何生成,具体处理委托给了determineBeanNameFromAnnotation(AnnotatedBeanDefinition)方法完成,该方法对该类的所有注解进行了遍历,满足三个条件:注解名称在待解析列表,存在value属性且非空,当且只有一个注解正确配置value属性。
/**
* Derive a bean name from one of the annotations on the class.
* 从类的注解中包含value属性的注解生成一个bean name
* @param annotatedDef the annotation-aware bean definition
* @return the bean name, or {@code null} if none is found
*/
protected String determineBeanNameFromAnnotation(AnnotatedBeanDefinition annotatedDef) {
//获取注解类元信息
AnnotationMetadata amd = annotatedDef.getMetadata();
//一个类存在多个注解,故类型为集合
Set<String> types = amd.getAnnotationTypes();
String beanName = null;
for (String type : types) {
//获取该类型对应的属性
AnnotationAttributes attributes = MetadataUtils.attributesFor(amd, type);
//判断注解类型是否包含value属性
if (isStereotypeWithNameValue(type, amd.getMetaAnnotationTypes(type), attributes)) {
String value = (String) attributes.get("value");
if (StringUtils.hasLength(value)) {
//不多于1个注解配置了value属性且非空,比如无法在一个类上面同时使用Component和Sevice注解同时配置beanName值
if (beanName != null && !value.equals(beanName)) {
throw new IllegalStateException("Stereotype annotations suggest inconsistent " +
"component names: '" + beanName + "' versus '" + value + "'");
}
beanName = value;
}
}
}
return beanName;
}
这个方法里面有两个关键的处理流程,第一步,读取对应annotationType对应的所有属性。
public static AnnotationAttributes attributesFor(AnnotationMetadata metadata, String annoClassName) {
return AnnotationAttributes.fromMap(metadata.getAnnotationAttributes(annoClassName, false));
}
//AnnotationMetadata.java
/**
* Retrieve the attributes of the annotation of the given type,
* if any (i.e. if defined on the underlying class, as direct
* annotation or as meta-annotation).
* @param annotationType the annotation type to look for
* @param classValuesAsString whether to convert class references to String
* class names for exposure as values in the returned Map, instead of Class
* references which might potentially have to be loaded first
* @return a Map of attributes, with the attribute name as key (e.g. "value")
* and the defined attribute value as Map value. This return value will be
* {@code null} if no matching annotation is defined.
*/
Map<String, Object> getAnnotationAttributes(String annotationType, boolean classValuesAsString);
第二步,判断annotationType是否具有value属性,但是metaAnnotationTypes.contains(COMPONENT_ANNOTATION_CLASSNAME)这部分并不是很懂?注解无法继承,为啥要多判断一次?
private static final String COMPONENT_ANNOTATION_CLASSNAME = "org.springframework.stereotype.Component";
/**
* Check whether the given annotation is a stereotype that is allowed
* to suggest a component name through its annotation {@code value()}.
* @param annotationType the name of the annotation class to check
* @param metaAnnotationTypes the names of meta-annotations on the given annotation
* @param attributes the map of attributes for the given annotation
* @return whether the annotation qualifies as a stereotype with component name
*/
protected boolean isStereotypeWithNameValue(String annotationType,Set<String> metaAnnotationTypes, Map<String, Object> attributes) { boolean isStereotype = annotationType.equals(COMPONENT_ANNOTATION_CLASSNAME) ||
(metaAnnotationTypes != null && metaAnnotationTypes.contains(COMPONENT_ANNOTATION_CLASSNAME)) ||
annotationType.equals("javax.annotation.ManagedBean") ||
annotationType.equals("javax.inject.Named");
return (isStereotype && attributes != null && attributes.containsKey("value"));
}
整理下思路:
生成bean name有两条处理线,使用AnnotationBeanDefinition注解和不使用的。
不使用AnnotationBeanDefinition注解的,直接将类名(不含包名)改为驼峰形式作为bean name。
使用AnnotationBeanDefinition注解的:
1,读取所有注解类型
2,便利所有注解类型,找到所有为Component、Service,Respository,Controller含有非空value属性的注解
3,不多于一个个有效配置时生效,大于一个会抛出异常。(spring无法明确具体哪个生效)
Spring源码入门——AnnotationBeanNameGenerator解析的更多相关文章
- Spring源码入门——DefaultBeanNameGenerator解析 转发 https://www.cnblogs.com/jason0529/p/5272265.html
Spring源码入门——DefaultBeanNameGenerator解析 我们知道在spring中每个bean都要有一个id或者name标示每个唯一的bean,在xml中定义一个bean可以指 ...
- Spring源码入门——XmlBeanDefinitionReader解析
接上篇[] ,我们看到BeanDefinitionReader解决的是从资源文件(xml,propert)到BeanDefinition集合的过程.所以BeanDefinitionReader接口有两 ...
- Spring源码入门——DefaultBeanNameGenerator解析
我们知道在spring中每个bean都要有一个id或者name标示每个唯一的bean,在xml中定义一个bean可以指定其id和name值,但那些没有指定的,或者注解的spring的beanname怎 ...
- 从零开始学spring源码之xml解析(一):入门
谈到spring,首先想到的肯定是ioc,DI依赖注入,aop,但是其实很多人只是知道这些是spring核心概念,甚至不知道这些代表了什么意思,,作为一个java程序员,怎么能说自己对号称改变了jav ...
- 从零开始学spring源码之xml解析(二):默认标签和自定义标签解析
默认标签: 上一篇说到spring的默认标签和自定义标签,发现这里面东西还蛮多的.决定还是拆开来写.今天就来好好聊聊这两块是怎么玩的,首先我们先看看默认标签: private void parseDe ...
- Spring源码-入门
一.测试类 public class Main { public static void main(String[] args) { ApplicationContext applicationCon ...
- spring 源码解析
1. [文件] spring源码.txt ~ 15B 下载(167) ? 1 springн┤┬вио╬Ш: 2. [文件] spring源码分析之AOP.txt ~ 15KB 下载( ...
- Spring源码深度解析
Spring源码分析 Spring Web入门及源码学习 [Spring源码分析]Bean加载流程概览 Spring Framework 实现原理与源码解析系统 Spring源码分析--水门 Spri ...
- Spring源码解析02:Spring IOC容器之XmlBeanFactory启动流程分析和源码解析
一. 前言 Spring容器主要分为两类BeanFactory和ApplicationContext,后者是基于前者的功能扩展,也就是一个基础容器和一个高级容器的区别.本篇就以BeanFactory基 ...
随机推荐
- js add media query
var msViewportStyle = document.createElement("style"); msViewportStyle.appendChild( docume ...
- IIS Handler and Module探索
Create Handler & Module Run the Visual Studio Create a Class Library “HMHandler” --> Change t ...
- Codeforces Round #326 div2
Problem_A(588A): 题意: Duff 很喜欢吃肉, 每天都要吃,然而她又懒得下楼. 可以买很多放在家里慢慢吃.然而肉价每天都在变化,现给定一个n, 表示有多少天,然后第i天吃ai kg的 ...
- 给新人follow代码想到的
这两天让新人(刚毕业,此前未接触前端)切了个页面,发现了一些问题,联想到自己初入前端的时候因为没人带不可避免的也走了很多弯路,所以借着跟他讲解的机会,在这里把新人切页面中常见的问题和不好的习惯列举一下 ...
- CSS3制作下拉菜单
导航菜单其实是没有什么可说的,制作方法到处可见,今天这个案例本来不只是一个导 航,还有一个搜索表单的,可是为了偷懒,把搜索表单部分去掉了,就变成了一个CSS3 制作的下拉菜单.在这个导航中主要两点,一 ...
- 对C语言中sizeof细节的三点分析
转自对C语言中sizeof细节的三点分析 1.sizeof是运算符,跟加减乘除的性质其实是一样的,在编译的时候进行执行,而不是在运行时才执行. 那么如果编程中验证这一点呢?ps:这是前两天朋友淘宝面试 ...
- loadrunner 怎么能得到返回的http状态?
loadrunner如何保存从服务器传回来的http头的信息? Action() { int HttpRetCode; web_url("www.hao123.com", &quo ...
- UVA 125 Numbering Paths
题目大意:给定n条单向边,求图中任意两点的连通路径的数目.其中点是从0-输入中出现的最大的点. 可以用floyd-warshall算法或者dfs. for(int k = 0; k < n; k ...
- 实时时钟、系统时钟和CPU时钟的区别
http://blog.sina.com.cn/s/blog_68f909c30100pli7.html 实时时钟:RTC时钟,用于提供年.月.日.时.分.秒和星期等的实时时间信息,由后备电池供电,当 ...
- 近期刷题的c语言总结。
首先是三个数学函数... /* 函数名: floor 功 能: 下舍入,返回小于或者等于指定表达式的最大整数 说明:返回x的下限,如74.12的下限为74,-74.12的下限为-75.返回值为floa ...