Spring对注解(Annotation)处理源码分析1——扫描和读取Bean定义 .
public class AnnotationConfigApplicationContext extends GenericApplicationContext {//创建一个读取注解的Bean定义读取器,并将其设置到容器中private final AnnotatedBeanDefinitionReader reader = new AnnotatedBeanDefinitionReader(this);//创建一个扫描指定类路径中注解Bean定义的扫描器,并将其设置到容器中private final ClassPathBeanDefinitionScanner scanner = new ClassPathBeanDefinitionScanner(this);//默认构造函数,初始化一个空容器,容器不包含任何 Bean 信息,需要在稍后通过调用其register() //方法注册配置类,并调用refresh()方法刷新容器,触发容器对注解Bean的载入、解析和注册过程public AnnotationConfigApplicationContext() {}//最常用的构造函数,通过将涉及到的配置类传递给该构造函数,以实现将相应配置类中的Bean//自动注册到容器中public AnnotationConfigApplicationContext(Class<?>... annotatedClasses) {register(annotatedClasses);refresh();}//该构造函数会自动扫描以给定的包及其子包下的所有类,并自动识别所有的Spring Bean,将其//注册到容器中public AnnotationConfigApplicationContext(String... basePackages) {scan(basePackages);refresh();}//为容器的注解Bean读取器和注解Bean扫描器设置Bean名称产生器public void setBeanNameGenerator(BeanNameGenerator beanNameGenerator) {this.reader.setBeanNameGenerator(beanNameGenerator);this.scanner.setBeanNameGenerator(beanNameGenerator);}//为容器的注解Bean读取器和注解Bean扫描器设置作用范围元信息解析器public void setScopeMetadataResolver(ScopeMetadataResolver scopeMetadataResolver) {this.reader.setScopeMetadataResolver(scopeMetadataResolver);this.scanner.setScopeMetadataResolver(scopeMetadataResolver);}//为容器注册一个要被处理的注解Bean,新注册的Bean,必须手动调用容器的//refresh()方法刷新容器,触发容器对新注册的Bean的处理public void register(Class<?>... annotatedClasses) {this.reader.register(annotatedClasses);}//扫描指定包路径及其子包下的注解类,为了使新添加的类被处理,必须手动调用//refresh()方法刷新容器public void scan(String... basePackages) {this.scanner.scan(basePackages);}}?
?
//注册多个注解Bean定义类public void register(Class<?>... annotatedClasses) {for (Class<?> annotatedClass : annotatedClasses) {registerBean(annotatedClass);}}//注册一个注解Bean定义类public void registerBean(Class<?> annotatedClass) {registerBean(annotatedClass, null, (Class<? extends Annotation>[]) null);}//Bean定义读取器注册注解Bean定义的入口方法public void registerBean(Class<?> annotatedClass, Class<? extends Annotation>... qualifiers) {registerBean(annotatedClass, null, qualifiers);}//Bean定义读取器向容器注册注解Bean定义类public void registerBean(Class<?> annotatedClass, String name, Class<? extends Annotation>... qualifiers) {//根据指定的注解Bean定义类,创建Spring容器中对注解Bean的封装的数据结构AnnotatedGenericBeanDefinition abd = new AnnotatedGenericBeanDefinition(annotatedClass);//解析注解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定义时,使用了额外的限定符注解,则解析限定符注解。//主要是配置的关于autowiring自动依赖注入装配的限定条件,即@Qualifier//注解,Spring自动依赖注入装配默认是按类型装配,如果使用@Qualifier则按名称if (qualifiers != null) {for (Class<? extends Annotation> qualifier : qualifiers) {//如果配置了@Primary注解,设置该Bean为autowiring自动依赖注入装//配时的首选if (Primary.class.equals(qualifier)) {abd.setPrimary(true);}//如果配置了@Lazy注解,则设置该Bean为非延迟初始化,如果没有配置,//则该Bean为预实例化else if (Lazy.class.equals(qualifier)) {abd.setLazyInit(true);}//如果使用了除@Primary和@Lazy以外的其他注解,则为该Bean添加一//个autowiring自动依赖注入装配限定符,该Bean在进autowiring//自动依赖注入装配时,根据名称装配限定符指定的Beanelse {abd.addQualifier(new AutowireCandidateQualifier(qualifier));}}}//创建一个指定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定义类中的作用域元信息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集合中Map<String, Object> attributes =annDef.getMetadata().getAnnotationAttributes(this.scopeAnnotationType.getName());//将获取到的@Scope注解的值设置到要返回的对象中if (attributes != null) {metadata.setScopeName((String) attributes.get("value"));//获取@Scope注解中的proxyMode属性值,在创建代理对象时会用到ScopedProxyMode proxyMode = (ScopedProxyMode) attributes.get("proxyMode");//如果@Scope的proxyMode属性值为null、DEFAULT或者NOif (proxyMode == null || proxyMode == ScopedProxyMode.DEFAULT) {//设置proxyMode为NOproxyMode = this.defaultProxyMode;}//为返回的元数据设置proxyModemetadata.setScopedProxyMode(proxyMode);}}//返回解析的作用域元信息对象return metadata;}?
?
//处理Bean定义中通用注解static void processCommonDefinitionAnnotations(AnnotatedBeanDefinition abd) {//如果Bean定义中有@Primary注解,则为该Bean设置为autowiring自动依赖注入//装配的首选对象if (abd.getMetadata().isAnnotated(Primary.class.getName())) {abd.setPrimary(true);}//如果Bean定义中有@Lazy注解,则将该Bean预实例化属性设置为@lazy注解的值if (abd.getMetadata().isAnnotated(Lazy.class.getName())) {Boolean value = (Boolean) abd.getMetadata().getAnnotationAttributes(Lazy.class.getName()).get("value");abd.setLazyInit(value);}//如果Bean定义中有@ DependsOn注解,则为该Bean设置所依赖的Bean名称,//容器将确保在实例化该Bean之前首先实例化所依赖的Bean if (abd.getMetadata().isAnnotated(DependsOn.class.getName())) {String[] value = (String[]) abd.getMetadata().getAnnotationAttributes(DependsOn.class.getName()).get("value");abd.setDependsOn(value);}}?
?
//根据作用域为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,则返回falseboolean proxyTargetClass = scopedProxyMode.equals(ScopedProxyMode.TARGET_CLASS);//为注册的Bean创建相应模式的代理对象return ScopedProxyCreator.createScopedProxy(definition, registry, proxyTargetClass);} ?
?
@Target(ElementType.TYPE)@Retention(RetentionPolicy.RUNTIME)@Documentedpublic @interface Component {String value() default "";}?
?
@Target({ElementType.TYPE})@Retention(RetentionPolicy.RUNTIME)@Documented@Componentpublic @interface Service {String value() default "";}?
?
@Target({ElementType.TYPE})@Retention(RetentionPolicy.RUNTIME)@Documented@Componentpublic @interface Controller {String value() default "";}
?
@Target({ElementType.TYPE})@Retention(RetentionPolicy.RUNTIME)@Documented@Componentpublic @interface Repository {String value() default "";}?
?
public class ClassPathBeanDefinitionScanner extends ClassPathScanningCandidateComponentProvider {//创建一个类路径Bean定义扫描器public ClassPathBeanDefinitionScanner(BeanDefinitionRegistry registry) {this(registry, true);}//为容器创建一个类路径Bean定义扫描器,并指定是否使用默认的扫描过滤规则。//即Spring默认扫描配置:@Component、@Repository、@Service、@Controller//注解的Bean,同时也支持JavaEE6的@ManagedBean和JSR-330的@Named注解public ClassPathBeanDefinitionScanner(BeanDefinitionRegistry registry, boolean useDefaultFilters) {//调用父类ClassPathScanningCandidateComponentProvider构造方法设置过滤规则super(useDefaultFilters);Assert.notNull(registry, "BeanDefinitionRegistry must not be null");//为容器设置加载Bean定义的注册器this.registry = registry;//如果注册器是资源加载器,则为容器设置资源加载器if (this.registry instanceof ResourceLoader) {setResourceLoader((ResourceLoader) this.registry);}}//调用类路径Bean定义扫描器入口方法public int scan(String... basePackages) {//获取容器中已经注册的Bean个数int beanCountAtScanStart = this.registry.getBeanDefinitionCount();//启动扫描器扫描给定包doScan(basePackages);//注册注解配置(Annotation config)处理器if (this.includeAnnotationConfig) {AnnotationConfigUtils.registerAnnotationConfigProcessors(this.registry);}//返回注册的Bean个数return this.registry.getBeanDefinitionCount() - beanCountAtScanStart;}//类路径Bean定义扫描器扫描给定包及其子包protected Set<BeanDefinitionHolder> doScan(String... basePackages) {//创建一个集合,存放扫描到Bean定义的封装类Set<BeanDefinitionHolder> beanDefinitions = new LinkedHashSet<BeanDefinitionHolder>();//遍历扫描所有给定的包for (String basePackage : basePackages) {//调用父类ClassPathScanningCandidateComponentProvider的方法//扫描给定类路径,获取符合条件的Bean定义Set<BeanDefinition> candidates = findCandidateComponents(basePackage);//遍历扫描到的Beanfor (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);//向容器注册扫描到的BeanregisterBeanDefinition(definitionHolder, this.registry);}}}return beanDefinitions;}……}?
?
public class ClassPathScanningCandidateComponentProvider implements ResourceLoaderAware {//保存过滤规则要包含的注解,即Spring默认的@Component、@Repository、@Service、//@Controller注解的Bean,以及JavaEE6的@ManagedBean和JSR-330的@Named注解private final List<TypeFilter> includeFilters = new LinkedList<TypeFilter>();//保存过滤规则要排除的注解private final List<TypeFilter> excludeFilters = new LinkedList<TypeFilter>();//构造方法,该方法在子类ClassPathBeanDefinitionScanner的构造方法中被调用public ClassPathScanningCandidateComponentProvider(boolean useDefaultFilters) {//如果使用Spring默认的过滤规则,则向容器注册过滤规则if (useDefaultFilters) {registerDefaultFilters();}}//向容器注册过滤规则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>) cl.loadClass("javax.annotation.ManagedBean")), false));logger.info("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>) cl.loadClass("javax.inject.Named")), false));logger.info("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) {//创建存储扫描到的类的集合Set<BeanDefinition> candidates = new LinkedHashSet<BeanDefinition>();try {//解析给定的包路径,this.resourcePattern=” **/*.class”,//ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX=“classpath:”//resolveBasePackage方法将包名中的”.”转换为文件系统的”/”String packageSearchPath = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX +resolveBasePackage(basePackage) + "/" + this.resourcePattern;//将给定的包路径解析为Spring资源对象Resource[] resources = this.resourcePatternResolver.getResources(packageSearchPath);boolean traceEnabled = logger.isTraceEnabled();boolean debugEnabled = logger.isDebugEnabled();//遍历扫描到的资源for (Resource resource : resources) {if (traceEnabled) {logger.trace("Scanning " + resource);}if (resource.isReadable()) {try {//为指定资源获取元数据读取器,元信息读取器通过汇编(ASM)读//取资源元信息MetadataReader metadataReader = this.metadataReaderFactory.getMetadataReader(resource);//如果扫描到的类符合容器配置的过滤规则if (isCandidateComponent(metadataReader)) {//通过汇编(ASM)读取资源字节码中的Bean定义元信息ScannedGenericBeanDefinition sbd = new ScannedGenericBeanDefinition(metadataReader);//设置Bean定义来源于resourcesbd.setResource(resource);//为元数据元素设置配置资源对象sbd.setSource(resource);//检查Bean是否是一个可实例化的对象if (isCandidateComponent(sbd)) {if (debugEnabled) {logger.debug("Identified candidate component class: " + resource);}candidates.add(sbd);}else {if (debugEnabled) {logger.debug("Ignored because not a concrete top-level class: " + resource);}}}else {if (traceEnabled) {logger.trace("Ignored because not matching any filter: " + resource);}}}catch (Throwable ex) {throw new BeanDefinitionStoreException("Failed to read candidate component class: " + resource, ex);}}else {if (traceEnabled) {logger.trace("Ignored because not readable: " + resource);}}}}catch (IOException ex) {throw new BeanDefinitionStoreException("I/O failure during classpath scanning", ex);}return candidates;}//判断元信息读取器读取的类是否符合容器定义的注解过滤规则protected boolean isCandidateComponent(MetadataReader metadataReader) throws IOException {//如果读取的类的注解在排除注解过滤规则中,返回falsefor (TypeFilter tf : this.excludeFilters) {if (tf.match(metadataReader, this.metadataReaderFactory)) {return false;}}//如果读取的类的注解在包含的注解的过滤规则中,则返回turefor (TypeFilter tf : this.includeFilters) {if (tf.match(metadataReader, this.metadataReaderFactory)) {return true;}}//如果读取的类的注解既不在排除规则,也不在包含规则中,则返回falsereturn false;}……}?
?
//载入注解Bean定义资源protected void loadBeanDefinitions(DefaultListableBeanFactory beanFactory) {//为容器设置注解Bean定义读取器AnnotatedBeanDefinitionReader reader = new AnnotatedBeanDefinitionReader(beanFactory);//为容器设置类路径Bean定义扫描器ClassPathBeanDefinitionScanner scanner = new ClassPathBeanDefinitionScanner(beanFactory);//获取容器的Bean名称生成器BeanNameGenerator beanNameGenerator = getBeanNameGenerator();//获取容器的作用域元信息解析器ScopeMetadataResolver scopeMetadataResolver = getScopeMetadataResolver();//为注解Bean定义读取器和类路径扫描器设置Bean名称生成器if (beanNameGenerator != null) {reader.setBeanNameGenerator(beanNameGenerator);scanner.setBeanNameGenerator(beanNameGenerator);}//为注解Bean定义读取器和类路径扫描器设置作用域元信息解析器if (scopeMetadataResolver != null) {reader.setScopeMetadataResolver(scopeMetadataResolver);scanner.setScopeMetadataResolver(scopeMetadataResolver);}//获取容器定义的Bean定义资源路径String[] configLocations = getConfigLocations();//如果定位的Bean定义资源路径不为空if (configLocations != null) {for (String configLocation : configLocations) {try {//使用当前容器的类加载器加载定位路径的字节码类文件Class<?> clazz = getClassLoader().loadClass(configLocation);if (logger.isInfoEnabled()) {logger.info("Successfully resolved class for [" + configLocation + "]");}reader.register(clazz);}catch (ClassNotFoundException ex) {if (logger.isDebugEnabled()) {logger.debug("Could not load class for config location [" + configLocation +"] - trying package scan. " + ex);}//如果容器类加载器加载定义路径的Bean定义资源失败,则启用//容器类路径扫描器扫描给定路径包及其子包中的类int count = scanner.scan(configLocation);if (logger.isInfoEnabled()) {if (count == 0) {logger.info("No annotated classes found for specified class/package [" + configLocation + "]");}else {logger.info("Found " + count + " annotated classes in package [" + configLocation + "]");}}}}}}?
?
?
?