• 【转】【Spring实战】Spring注解配置工作原理源码解析


    一、背景知识

    【Spring实战】Spring容器初始化完成后执行初始化数据方法一文中说要分析其实现原理,于是就从源码中寻找答案,看源码容易跑偏,因此应当有个主线,或者带着问题、目标去看,这样才能最大限度的提升自身代码水平。由于上文中大部分都基于注解进行设置的(Spring实战系列篇demo大部分也都是基于注解实现的),因此就想弄明白Spring中注解是怎么工作的,这个也是分析上文中实现原理的一个基础。于是索性解析下Spring中注解的工作原理。
     

    二、从context:component-scan标签或@ComponentScan注解说起

    如果想要使用Spring注解,那么首先要在配置文件中配置context:component-scan标签或者在配置类中添加@ComponentScan注解。题外话:现在Spring已经完全可以实现无xml(当然有些还是需要xml配置来实现的)的配置,甚至都不需要web.xml,当然这需要Servlet3.0服务器的支持(如Tomcat7或者更高版本)。Spirng In Action Fourth是针对三种bean的装配机制(xml进行显示配置、java中进行显示配置、隐式的bean发现机制和自动装配)的使用是这样建议的:
     
     
    如果要使用自动配置机制,就要在配置文件中配置context:component-scan标签或者在配置类中添加@ComponentScan注解。基于【Spring实战】----Spring配置文件的解析
    篇文章,本文还是基于xml中的自定义标签进行解析,当然也可以直接看@ComponentScan注解的解析(ComponentScanAnnotationParser.java,这其中还牵扯到@Configuration以及另外的知识点)。
     

    三、context:component-scan标签解析

    以实战篇系列demo为例进行分析
    1. <context:component-scan base-package="com.mango.jtt"></context:component-scan>  


    【Spring实战】----Spring配置文件的解析中可知,标签的处理器为spring.handlers
    1. http://www.springframework.org/schema/context=org.springframework.context.config.ContextNamespaceHandler  
    1. registerBeanDefinitionParser("component-scan", new ComponentScanBeanDefinitionParser());  

    在ComponentScanBeanDefinitionParser.java中进行处理
     
    1. @Override  
    2.     public BeanDefinition parse(Element element, ParserContext parserContext) {  
    3.         String basePackage = element.getAttribute(BASE_PACKAGE_ATTRIBUTE);  
    4.         basePackage = parserContext.getReaderContext().getEnvironment().resolvePlaceholders(basePackage);  
    5.         String[] basePackages = StringUtils.tokenizeToStringArray(basePackage,  
    6.                 ConfigurableApplicationContext.CONFIG_LOCATION_DELIMITERS);  
    7.   
    8.         // Actually scan for bean definitions and register them.  
    9.         ClassPathBeanDefinitionScanner scanner = configureScanner(parserContext, element);    //得到扫描器  
    10.         Set<BeanDefinitionHolder> beanDefinitions = scanner.doScan(basePackages);             //扫描文件,并转化为spring bean,并注册  
    11.         registerComponents(parserContext.getReaderContext(), beanDefinitions, element);       //注册其他相关组件  
    12.   
    13.         return null;  
    14.     }  

    从上述代码中可知,其作用就是扫描basePackages下的文件,转化为spring中的bean结构,并将其注册到容器中;最后是注册相关组件(主要是注解处理器)。注解需要注解处理器来处理。
     
    要知道ComponentScanBeanDefinitionParser扫描文件并转化成spring bean的原则的,就需要看下其定义的属性值:
    1. private static final String BASE_PACKAGE_ATTRIBUTE = "base-package";  
    2.   
    3.     private static final String RESOURCE_PATTERN_ATTRIBUTE = "resource-pattern";  
    4.   
    5.     private static final String USE_DEFAULT_FILTERS_ATTRIBUTE = "use-default-filters";  
    6.   
    7.     private static final String ANNOTATION_CONFIG_ATTRIBUTE = "annotation-config";  
    8.   
    9.     private static final String NAME_GENERATOR_ATTRIBUTE = "name-generator";  
    10.   
    11.     private static final String SCOPE_RESOLVER_ATTRIBUTE = "scope-resolver";  
    12.   
    13.     private static final String SCOPED_PROXY_ATTRIBUTE = "scoped-proxy";  
    14.   
    15.     private static final String EXCLUDE_FILTER_ELEMENT = "exclude-filter";  
    16.   
    17.     private static final String INCLUDE_FILTER_ELEMENT = "include-filter";  
    18.   
    19.     private static final String FILTER_TYPE_ATTRIBUTE = "type";  
    20.   
    21.     private static final String FILTER_EXPRESSION_ATTRIBUTE = "expression";  

    先简单解析下上述属性的作用
     
    • base-package:为必须配置属性,指定了spring需要扫描的跟目录名称,可以使用”,” “;” “ (回车符)”来分割多个包名
    • resource-pattern:配置扫描资源格式.默认”**/*.class
    • use-default-filters:是否使用默认扫描策略,默认为”true”,会自动扫描指定包下的添加了如下注解的类,@Component, @Repository, @Service,or @Controller

    • annotation-config:是否启用默认配置,默认为”true”,该配置会在BeanDefinition注册到容器后自动注册一些BeanPostProcessors对象到容器中.这些处理器用来处理类中Spring’s @Required and 
      @Autowired, JSR 250’s @PostConstruct, @PreDestroy and @Resource (如果可用), 
      JAX-WS’s @WebServiceRef (如果可用), EJB 3’s @EJB (如果可用), and JPA’s 
      @PersistenceContext and @PersistenceUnit (如果可用),但是该属性不会处理Spring’s @Transactional 和 EJB 3中的@TransactionAttribute注解对象,这两个注解是通过<tx:annotation-driven>元素处理过程中对应的BeanPostProcessor来处理的.
    • include-filter:如果有自定义元素可以在该处配置
    • exclude-filter:配置哪些类型的类不需要扫描
    • 注意:</context:component-scan>元素中默认配置了annotation-config,所以不需要再单独配置</annotation-config>元素. 
    这些属性作用配置都是在configureScanner()函数中进行的。
    1. protected ClassPathBeanDefinitionScanner configureScanner(ParserContext parserContext, Element element) {  
    2.         boolean useDefaultFilters = true;  
    3.         if (element.hasAttribute(USE_DEFAULT_FILTERS_ATTRIBUTE)) {  
    4.             useDefaultFilters = Boolean.valueOf(element.getAttribute(USE_DEFAULT_FILTERS_ATTRIBUTE));       
    5.         }  
    6.   
    7.         // Delegate bean definition registration to scanner class.  
    8.         ClassPathBeanDefinitionScanner scanner = createScanner(parserContext.getReaderContext(), useDefaultFilters);   //包含了扫描策略配置  
    9.         scanner.setResourceLoader(parserContext.getReaderContext().getResourceLoader());  
    10.         scanner.setEnvironment(parserContext.getReaderContext().getEnvironment());  
    11.         scanner.setBeanDefinitionDefaults(parserContext.getDelegate().getBeanDefinitionDefaults());  
    12.         scanner.setAutowireCandidatePatterns(parserContext.getDelegate().getAutowireCandidatePatterns());  
    13.   
    14.         if (element.hasAttribute(RESOURCE_PATTERN_ATTRIBUTE)) {  
    15.             scanner.setResourcePattern(element.getAttribute(RESOURCE_PATTERN_ATTRIBUTE));        //配置扫描资源格式  
    16.         }  
    17.   
    18.         try {  
    19.             parseBeanNameGenerator(element, scanner);                                    //配置名称生成器  
    20.         }  
    21.         catch (Exception ex) {  
    22.             parserContext.getReaderContext().error(ex.getMessage(), parserContext.extractSource(element), ex.getCause());  
    23.         }  
    24.   
    25.         try {  
    26.             parseScope(element, scanner);                                     //配置元数据解析器  
    27.         }  
    28.         catch (Exception ex) {  
    29.             parserContext.getReaderContext().error(ex.getMessage(), parserContext.extractSource(element), ex.getCause());  
    30.         }  
    31.   
    32.         parseTypeFilters(element, scanner, parserContext);                      //配置包含和不包含过滤  
    33.   
    34.         return scanner;  
    35.     }  
     
    看一下默认扫描策略的配置
    1. /** 
    2.      * Register the default filter for {@link Component @Component}. 
    3.      * <p>This will implicitly register all annotations that have the 
    4.      * {@link Component @Component} meta-annotation including the 
    5.      * {@link Repository @Repository}, {@link Service @Service}, and 
    6.      * {@link Controller @Controller} stereotype annotations. 
    7.      * <p>Also supports Java EE 6's {@link javax.annotation.ManagedBean} and 
    8.      * JSR-330's {@link javax.inject.Named} annotations, if available. 
    9.      * 
    10.      */  
    11.     @SuppressWarnings("unchecked")  
    12.     protected void registerDefaultFilters() {  
    13.         this.includeFilters.add(new AnnotationTypeFilter(Component.class));  
    14.         ClassLoader cl = ClassPathScanningCandidateComponentProvider.class.getClassLoader();  
    15.         try {  
    16.             this.includeFilters.add(new AnnotationTypeFilter(  
    17.                     ((Class<? extends Annotation>) ClassUtils.forName("javax.annotation.ManagedBean", cl)), false));  
    18.             logger.debug("JSR-250 'javax.annotation.ManagedBean' found and supported for component scanning");  
    19.         }  
    20.         catch (ClassNotFoundException ex) {  
    21.             // JSR-250 1.1 API (as included in Java EE 6) not available - simply skip.  
    22.         }  
    23.         try {  
    24.             this.includeFilters.add(new AnnotationTypeFilter(  
    25.                     ((Class<? extends Annotation>) ClassUtils.forName("javax.inject.Named", cl)), false));  
    26.             logger.debug("JSR-330 'javax.inject.Named' annotation found and supported for component scanning");  
    27.         }  
    28.         catch (ClassNotFoundException ex) {  
    29.             // JSR-330 API not available - simply skip.  
    30.         }  
    31.     }  
    从注释中看出除了,@Component、和包含元注解@Component的@Controller、@Service、@Repository,还支持Java EE 6的@link javax.annotation.ManagedBean和jsr - 330的 @link javax.inject.Named,如果可用。
    - 默认过滤器主要扫描@Component @Repository @Service @Controller注解的类,同样可以通过配置类扫描过滤器来扫描自定义注解的类。 
    - 当类路径下有javax.annotation.ManagedBean和javax.inject.Named类库时支持这2个注解扫描。


    其扫描过程如下:
    - 首先构造一个ClassPathBeanDefinitionScanner对象,需要传递一个BeanDefinitionRegistry对象。 
    - 根据配置文件配置属性设置scanner的扫描属性,比如”resource-pattern”, “name-generator”, “scope-resolver”等。 
    - 调用scanner.doScan(String… basePackages)方法完成候选类的自动扫描。 
     
    下面看一下doScan
    1. /** 
    2.      * Perform a scan within the specified base packages, 
    3.      * returning the registered bean definitions. 
    4.      * <p>This method does <i>not</i> register an annotation config processor 
    5.      * but rather leaves this up to the caller. 
    6.      * @param basePackages the packages to check for annotated classes 
    7.      * @return set of beans registered if any for tooling registration purposes (never {@code null}) 
    8.      */  
    9.     protected Set<BeanDefinitionHolder> doScan(String... basePackages) {  
    10.         Assert.notEmpty(basePackages, "At least one base package must be specified");  
    11.         Set<BeanDefinitionHolder> beanDefinitions = new LinkedHashSet<BeanDefinitionHolder>();  
    12.         for (String basePackage : basePackages) {  
    13.             Set<BeanDefinition> candidates = findCandidateComponents(basePackage);  
    14.             for (BeanDefinition candidate : candidates) {  
    15.                 ScopeMetadata scopeMetadata = this.scopeMetadataResolver.resolveScopeMetadata(candidate);  
    16.                 candidate.setScope(scopeMetadata.getScopeName());  
    17.                 String beanName = this.beanNameGenerator.generateBeanName(candidate, this.registry);  
    18.                 if (candidate instanceof AbstractBeanDefinition) {  
    19.                     postProcessBeanDefinition((AbstractBeanDefinition) candidate, beanName);    //配置bena属性  
    20.                 }  
    21.                 if (candidate instanceof AnnotatedBeanDefinition) {  
    22.                     AnnotationConfigUtils.processCommonDefinitionAnnotations((AnnotatedBeanDefinition) candidate); //配置通过注解设置的便属性  
    23.                 }  
    24.                 if (checkCandidate(beanName, candidate)) {  
    25.                     BeanDefinitionHolder definitionHolder = new BeanDefinitionHolder(candidate, beanName);  
    26.                     definitionHolder = AnnotationConfigUtils.applyScopedProxyMode(scopeMetadata, definitionHolder, this.registry);  
    27.                     beanDefinitions.add(definitionHolder);  
    28.                     registerBeanDefinition(definitionHolder, this.registry);  
    29.                 }  
    30.             }  
    31.         }  
    32.         return beanDefinitions;  
    33.     }  
     
    实际上扫描文件并包装成BeanDefinition是由findCandidateComponents来做的
    1. /** 
    2.      * Scan the class path for candidate components. 
    3.      * @param basePackage the package to check for annotated classes 
    4.      * @return a corresponding Set of autodetected bean definitions 
    5.      */  
    6.     public Set<BeanDefinition> findCandidateComponents(String basePackage) {  
    7.         Set<BeanDefinition> candidates = new LinkedHashSet<BeanDefinition>();  
    8.         try {  
    9.             String packageSearchPath = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX +  
    10.                     resolveBasePackage(basePackage) + "/" + this.resourcePattern;  
    11.             Resource[] resources = this.resourcePatternResolver.getResources(packageSearchPath);  
    12.             boolean traceEnabled = logger.isTraceEnabled();  
    13.             boolean debugEnabled = logger.isDebugEnabled();  
    14.             for (Resource resource : resources) {  
    15.                 if (traceEnabled) {  
    16.                     logger.trace("Scanning " + resource);  
    17.                 }  
    18.                 if (resource.isReadable()) {  
    19.                     try {  
    20.                         MetadataReader metadataReader = this.metadataReaderFactory.getMetadataReader(resource);  
    21.                         if (isCandidateComponent(metadataReader)) {  
    22.                             ScannedGenericBeanDefinition sbd = new ScannedGenericBeanDefinition(metadataReader);  
    23.                             sbd.setResource(resource);  
    24.                             sbd.setSource(resource);  
    25.                             if (isCandidateComponent(sbd)) {  
    26.                                 if (debugEnabled) {  
    27.                                     logger.debug("Identified candidate component class: " + resource);  
    28.                                 }  
    29.                                 candidates.add(sbd);  
    30.                             }  
    31.                             else {  
    32.                                 if (debugEnabled) {  
    33.                                     logger.debug("Ignored because not a concrete top-level class: " + resource);  
    34.                                 }  
    35.                             }  
    36.                         }  
    37.                         else {  
    38.                             if (traceEnabled) {  
    39.                                 logger.trace("Ignored because not matching any filter: " + resource);  
    40.                             }  
    41.                         }  
    42.                     }  
    43.                     catch (Throwable ex) {  
    44.                         throw new BeanDefinitionStoreException(  
    45.                                 "Failed to read candidate component class: " + resource, ex);  
    46.                     }  
    47.                 }  
    48.                 else {  
    49.                     if (traceEnabled) {  
    50.                         logger.trace("Ignored because not readable: " + resource);  
    51.                     }  
    52.                 }  
    53.             }  
    54.         }  
    55.         catch (IOException ex) {  
    56.             throw new BeanDefinitionStoreException("I/O failure during classpath scanning", ex);  
    57.         }  
    58.         return candidates;  
    59.     }  

    大致的流程如下:

    (1)先根据context:component-scan 中属性的base-package="com.mango.jtt"配置转换为classpath*:com/mango/jtt/**/*.class(默认格式),并扫描对应下的class和jar文件并获取类对应的路径,返回Resources

    (2)根据指定的不扫描包,指定的扫描包配置进行过滤不包含的包对应下的class和jar。

    (3)封装成BeanDefinition放到队列里。

    实际上,是把所有包下的class文件都扫描了的,并且利用asm技术读取java字节码并转化为MetadataReader中的AnnotationMetadataReadingVisitor结构
    1. MetadataReader metadataReader = this.metadataReaderFactory.getMetadataReader(resource);  

    1. SimpleMetadataReader(Resource resource, ClassLoader classLoader) throws IOException {  
    2.         InputStream is = new BufferedInputStream(resource.getInputStream());  
    3.         ClassReader classReader;  
    4.         try {  
    5.             classReader = new ClassReader(is);  
    6.         }  
    7.         catch (IllegalArgumentException ex) {  
    8.             throw new NestedIOException("ASM ClassReader failed to parse class file - " +  
    9.                     "probably due to a new Java class file version that isn't supported yet: " + resource, ex);  
    10.         }  
    11.         finally {  
    12.             is.close();  
    13.         }  
    14.   
    15.         AnnotationMetadataReadingVisitor visitor = new AnnotationMetadataReadingVisitor(classLoader);  
    16.         classReader.accept(visitor, ClassReader.SKIP_DEBUG);  
    17.   
    18.         this.annotationMetadata = visitor;  
    19.         // (since AnnotationMetadataReadingVisitor extends ClassMetadataReadingVisitor)  
    20.         this.classMetadata = visitor;  
    21.         this.resource = resource;  
    22.     }  

    此处不深究牛X的asm技术,继续看其两个if判断,只有符合这两个if的才add到candidates,也就是候选者BeanDefinition,函数名字起得名副其实。

    1. if (isCandidateComponent(metadataReader)) {  
    2.                             ScannedGenericBeanDefinition sbd = new ScannedGenericBeanDefinition(metadataReader);  
    3.                             sbd.setResource(resource);  
    4.                             sbd.setSource(resource);  
    5.                             if (isCandidateComponent(sbd)) {  
    6.                                 if (debugEnabled) {  
    7.                                     logger.debug("Identified candidate component class: " + resource);  
    8.                                 }  
    9.                                 candidates.add(sbd);  
    10.                             }  
    11.                             else {  
    12.                                 if (debugEnabled) {  
    13.                                     logger.debug("Ignored because not a concrete top-level class: " + resource);  
    14.                                 }  
    15.                             }  
    16.                         }  

    先看第一个判断
    1. /** 
    2.      * Determine whether the given class does not match any exclude filter 
    3.      * and does match at least one include filter. 
    4.      * @param metadataReader the ASM ClassReader for the class 
    5.      * @return whether the class qualifies as a candidate component 
    6.      */  
    7.     protected boolean isCandidateComponent(MetadataReader metadataReader) throws IOException {  
    8.         for (TypeFilter tf : this.excludeFilters) {  
    9.             if (tf.match(metadataReader, this.metadataReaderFactory)) {  
    10.                 return false;  
    11.             }  
    12.         }  
    13.         for (TypeFilter tf : this.includeFilters) {  
    14.             if (tf.match(metadataReader, this.metadataReaderFactory)) {  
    15.                 return isConditionMatch(metadataReader);  
    16.             }  
    17.         }  
    18.         return false;  
    19.     }  
    这里的判断就用到了前面说的属性设置,在本例中excludeFilters是没有内容的,includeFilters包含有@Component和@Named两个的AnnotationTypeFilter。因此只有第二个循环起作用,也就是是有符合@Component且元注解为@Component的注解和@Named两种注解的才可以。
     
    第二个if就是判断类是否是实现类,抽象类好接口类都不不可以
    1. /** 
    2.      * Determine whether the given bean definition qualifies as candidate. 
    3.      * <p>The default implementation checks whether the class is concrete 
    4.      * (i.e. not abstract and not an interface). Can be overridden in subclasses. 
    5.      * @param beanDefinition the bean definition to check 
    6.      * @return whether the bean definition qualifies as a candidate component 
    7.      */  
    8.     protected boolean isCandidateComponent(AnnotatedBeanDefinition beanDefinition) {  
    9.         return (beanDefinition.getMetadata().isConcrete() && beanDefinition.getMetadata().isIndependent());  
    10.     }  
    总结:扫描器采用asm技术扫描java字节码文件,即.class文件。扫描时是扫描指定包下的全部class文件,转换成指定的MetadataReader结构后,再去判断是否符合扫描规则,符合的才加入候选bean中,并注册到容器中。

    至此,注解扫描分析完了,看一下bean注册,回到doScan中
    1. if (checkCandidate(beanName, candidate)) {  
    2.                     BeanDefinitionHolder definitionHolder = new BeanDefinitionHolder(candidate, beanName);  
    3.                     definitionHolder = AnnotationConfigUtils.applyScopedProxyMode(scopeMetadata, definitionHolder, this.registry);  
    4.                     beanDefinitions.add(definitionHolder);  
    5.                     registerBeanDefinition(definitionHolder, this.registry);  
    6.                 }  
    也是只有符合条件的才注册,主要是容器中没有的,或者不和容器中有的冲突的。
     
    再看下其他组件注册,回到最初的parse
    1. registerComponents(parserContext.getReaderContext(), beanDefinitions, element);  

    1. protected void registerComponents(  
    2.             XmlReaderContext readerContext, Set<BeanDefinitionHolder> beanDefinitions, Element element) {  
    3.   
    4.         Object source = readerContext.extractSource(element);  
    5.         CompositeComponentDefinition compositeDef = new CompositeComponentDefinition(element.getTagName(), source);  
    6.   
    7.         for (BeanDefinitionHolder beanDefHolder : beanDefinitions) {  
    8.             compositeDef.addNestedComponent(new BeanComponentDefinition(beanDefHolder));  
    9.         }  
    10.   
    11.         // Register annotation config processors, if necessary.  
    12.         boolean annotationConfig = true;  
    13.         if (element.hasAttribute(ANNOTATION_CONFIG_ATTRIBUTE)) {  //本例中没有配置annotation-config,默认为true  
    14.             annotationConfig = Boolean.valueOf(element.getAttribute(ANNOTATION_CONFIG_ATTRIBUTE));  
    15.         }  
    16.         if (annotationConfig) {  
    17.             Set<BeanDefinitionHolder> processorDefinitions =  
    18.                     AnnotationConfigUtils.registerAnnotationConfigProcessors(readerContext.getRegistry(), source);  //注册注解处理器  
    19.             for (BeanDefinitionHolder processorDefinition : processorDefinitions) {  
    20.                 compositeDef.addNestedComponent(new BeanComponentDefinition(processorDefinition));  
    21.             }  
    22.         }  
    23.   
    24.         readerContext.fireComponentRegistered(compositeDef);         //目前没啥卵用,EmptyReaderEventListener.java中都是空操作,扩展用  
    25.     }  

    上述代码的作用主要是注册注解处理器,本例中没有配置annotation-config,默认值为true,这里也就说明了为什么配置了<context:component-scan>标签就不需要再配置<context:annotation-config>标签的原因。看下注册注解处理器:
    org.springframework.context.annotation.AnnotationConfigUtils.java
     
    1. /** 
    2.      * Register all relevant annotation post processors in the given registry. 
    3.      * @param registry the registry to operate on 
    4.      * @param source the configuration source element (already extracted) 
    5.      * that this registration was triggered from. May be {@code null}. 
    6.      * @return a Set of BeanDefinitionHolders, containing all bean definitions 
    7.      * that have actually been registered by this call 
    8.      */  
    9.     public static Set<BeanDefinitionHolder> registerAnnotationConfigProcessors(  
    10.             BeanDefinitionRegistry registry, Object source) {  
    11.   
    12.         DefaultListableBeanFactory beanFactory = unwrapDefaultListableBeanFactory(registry);  
    13.         if (beanFactory != null) {  
    14.             if (!(beanFactory.getDependencyComparator() instanceof AnnotationAwareOrderComparator)) {  
    15.                 beanFactory.setDependencyComparator(AnnotationAwareOrderComparator.INSTANCE);      //设置注解比较器,为Spring中的Order提供支持  
    16.             }  
    17.             if (!(beanFactory.getAutowireCandidateResolver() instanceof ContextAnnotationAutowireCandidateResolver)) {  
    18.                 beanFactory.setAutowireCandidateResolver(new ContextAnnotationAutowireCandidateResolver());   //设置AutowireCandidateResolver,为qualifier注解和lazy注解提供支持  
    19.             }  
    20.         }  
    21.   
    22.         Set<BeanDefinitionHolder> beanDefs = new LinkedHashSet<BeanDefinitionHolder>(4);  
    23.   
    24.         if (!registry.containsBeanDefinition(CONFIGURATION_ANNOTATION_PROCESSOR_BEAN_NAME)) {  
    25.             RootBeanDefinition def = new RootBeanDefinition(ConfigurationClassPostProcessor.class);  
    26.             def.setSource(source);  
    27.             beanDefs.add(registerPostProcessor(registry, def, CONFIGURATION_ANNOTATION_PROCESSOR_BEAN_NAME)); //注册@Configuration处理器  
    28.         }  
    29.   
    30.         if (!registry.containsBeanDefinition(AUTOWIRED_ANNOTATION_PROCESSOR_BEAN_NAME)) {  
    31.             RootBeanDefinition def = new RootBeanDefinition(AutowiredAnnotationBeanPostProcessor.class);  
    32.             def.setSource(source);  
    33.             beanDefs.add(registerPostProcessor(registry, def, AUTOWIRED_ANNOTATION_PROCESSOR_BEAN_NAME));//注册@Autowired、@Value、@Inject处理器  
    34.         }  
    35.   
    36.         if (!registry.containsBeanDefinition(REQUIRED_ANNOTATION_PROCESSOR_BEAN_NAME)) {  
    37.             RootBeanDefinition def = new RootBeanDefinition(RequiredAnnotationBeanPostProcessor.class);  
    38.             def.setSource(source);  
    39.             beanDefs.add(registerPostProcessor(registry, def, REQUIRED_ANNOTATION_PROCESSOR_BEAN_NAME));//注册@Required处理器<span style="white-space:pre">  </span>  
    40.         }  
    41.   
    42.         // Check for JSR-250 support, and if present add the CommonAnnotationBeanPostProcessor.  
    43.         if (jsr250Present && !registry.containsBeanDefinition(COMMON_ANNOTATION_PROCESSOR_BEAN_NAME)) {  
    44.             RootBeanDefinition def = new RootBeanDefinition(CommonAnnotationBeanPostProcessor.class);  
    45.             def.setSource(source);  
    46.             beanDefs.add(registerPostProcessor(registry, def, COMMON_ANNOTATION_PROCESSOR_BEAN_NAME));//在支持JSR-250条件下注册javax.annotation包下注解处理器,包括@PostConstruct、@PreDestroy、@Resource注解等  
    47.         }  
    48.   
    49.         // Check for JPA support, and if present add the PersistenceAnnotationBeanPostProcessor.  
    50.         if (jpaPresent && !registry.containsBeanDefinition(PERSISTENCE_ANNOTATION_PROCESSOR_BEAN_NAME)) {  
    51.             RootBeanDefinition def = new RootBeanDefinition();  
    52.             try {  
    53.                 def.setBeanClass(ClassUtils.forName(PERSISTENCE_ANNOTATION_PROCESSOR_CLASS_NAME,  
    54.                         AnnotationConfigUtils.class.getClassLoader()));  
    55.             }  
    56.             catch (ClassNotFoundException ex) {  
    57.                 throw new IllegalStateException(  
    58.                         "Cannot load optional framework class: " + PERSISTENCE_ANNOTATION_PROCESSOR_CLASS_NAME, ex);  
    59.             }  
    60.             def.setSource(source);  
    61.             beanDefs.add(registerPostProcessor(registry, def, PERSISTENCE_ANNOTATION_PROCESSOR_BEAN_NAME));//支持jpa的条件下,注册org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor处理器,处理jpa相关注解  
    62.         }  
    63.   
    64.         if (!registry.containsBeanDefinition(EVENT_LISTENER_PROCESSOR_BEAN_NAME)) {  
    65.             RootBeanDefinition def = new RootBeanDefinition(EventListenerMethodProcessor.class);  
    66.             def.setSource(source);  
    67.             beanDefs.add(registerPostProcessor(registry, def, EVENT_LISTENER_PROCESSOR_BEAN_NAME));//注册@EventListener处理器  
    68.         }  
    69.         if (!registry.containsBeanDefinition(EVENT_LISTENER_FACTORY_BEAN_NAME)) {  
    70.             RootBeanDefinition def = new RootBeanDefinition(DefaultEventListenerFactory.class);  
    71.             def.setSource(source);  
    72.             beanDefs.add(registerPostProcessor(registry, def, EVENT_LISTENER_FACTORY_BEAN_NAME));//注册支持@EventListener注解的处理器  
    73.         }  
    74.   
    75.         return beanDefs;  
    76.     }  


    真正的注册是如下函数:
    1. private static BeanDefinitionHolder registerPostProcessor(  
    2.             BeanDefinitionRegistry registry, RootBeanDefinition definition, String beanName) {  
    3.   
    4.         definition.setRole(BeanDefinition.ROLE_INFRASTRUCTURE);   //角色属于后台角色,框架内部使用,和最终用户无关  
    5.         registry.registerBeanDefinition(beanName, definition);    //也是注册到beanFactory中的beanDefinitionMap中,其实和注册bean一样,并且beanName是定义好了的  
    6.         return new BeanDefinitionHolder(definition, beanName);  
    7.     }  

    注册注解处理器的过程也是讲处理包装成RootBeanDefinition,放到beanFactory(这里是DefaultListableBeanFactory)中的beanDefinitionMap中。
     
    至此,标签<context:component-scan>的解析已经分析完了,总结如下:
    1)根据配置利用asm技术扫描.class文件,并将包含@Component及元注解为@Component的注解@Controller、@Service、@Repository或者还支持Java EE 6的@link javax.annotation.ManagedBean和jsr - 330的 @link javax.inject.Named,如果可用。的bean注册到beanFactory中
    2)注册注解后置处理器,主要是处理属性或方法中的注解,包含:
     注册@Configuration处理器ConfigurationClassPostProcessor,
    注册@Autowired、@Value、@Inject处理器AutowiredAnnotationBeanPostProcessor,
    注册@Required处理器RequiredAnnotationBeanPostProcessor、
    在支持JSR-250条件下注册javax.annotation包下注解处理器CommonAnnotationBeanPostProcessor,包括@PostConstruct、@PreDestroy、@Resource注解等、
    支持jpa的条件下,注册org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor处理器,处理jpa相关注解
    注册@EventListener处理器EventListenerMethodProcessor
     
    使用注解的.class文件也扫描完了,注解处理器也注册完了,那么注解是什么时候处理的呢?下一节会继续分析。


    四、注解处理器实例化

    要想使用注解处理器,必须要实例化注解处理器,那么其实例化是在哪里进行的呢,这里还需要回到org.springframework.context.support.AbstractApplicationContext.java中的refresh()函数
     
    1. @Override  
    2.     public void refresh() throws BeansException, IllegalStateException {  
    3.         synchronized (this.startupShutdownMonitor) {  
    4.             // Prepare this context for refreshing.  
    5.             prepareRefresh();   //初始化前的准备,例如对系统属性或者环境变量进行准备及验证  
    6.   
    7.             // Tell the subclass to refresh the internal bean factory.  
    8.             ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();  //初始化BeanFactory,解析xml配置文件,其中标签<context:component-scan>就是在这里解析的  
    9.   
    10.             // Prepare the bean factory for use in this context.  
    11.             prepareBeanFactory(beanFactory);  //配置工厂的标准上下文特征,例如上下文的类加载器和后处理器。  
    12.   
    13.             try {  
    14.                 // Allows post-processing of the bean factory in context subclasses.  
    15.                 postProcessBeanFactory(beanFactory);     //子类覆盖方法,做特殊处理,主要是后处理器相关  
    16.   
    17.                 // Invoke factory processors registered as beans in the context.  
    18.                 invokeBeanFactoryPostProcessors(beanFactory);  //激活各种beanFactory处理器,实例化并调用所有注册的BeanFactoryPostProcessor bean,  
    19. 如果给定的话,尊重显式的顺序。注意这里和扫描时的bean处理器的区别。  
    20.   
    21.                 // Register bean processors that intercept bean creation.  
    22.                 registerBeanPostProcessors(beanFactory); //<span style="color: rgb(46, 48, 51); font-family: Arial, "Microsoft YaHei", 微软雅黑, 宋体, "Malgun Gothic", Meiryo, sans-serif; line-height: 18px;">实例化并调用所有已注册的BeanPostProcessor bean,</span><span style="color: rgb(46, 48, 51); font-family: Arial, "Microsoft YaHei", 微软雅黑, 宋体, "Malgun Gothic", Meiryo, sans-serif; line-height: 18px;">如果给定的话,尊重显式的顺序。</span><br style="box-sizing: border-box; color: rgb(46, 48, 51); font-family: Arial, "Microsoft YaHei", 微软雅黑, 宋体, "Malgun Gothic", Meiryo, sans-serif; line-height: 18px;"><div class="br-height" style="box-sizing: border-box; margin: 0px; padding: 0px; height: 22px; display: inline-block; color: rgb(46, 48, 51); font-family: Arial, "Microsoft YaHei", 微软雅黑, 宋体, "Malgun Gothic", Meiryo, sans-serif; line-height: 18px;"></div><span style="color: rgb(46, 48, 51); font-family: Arial, "Microsoft YaHei", 微软雅黑, 宋体, "Malgun Gothic", Meiryo, sans-serif; line-height: 18px;">必须在应用程序bean的任何实例化之前调用它。这是本节的分析重点。这里就是实例化上面注册的bean处理器</span>  
    23.   
    24.                 // Initialize message source for this context.  
    25.                 initMessageSource();    //初始化消息资源,国际化等用  
    26.   
    27.                 // Initialize event multicaster for this context.  
    28.                 initApplicationEventMulticaster(); //初始化应用事件广播  
    29.   
    30.                 // Initialize other special beans in specific context subclasses.  
    31.                 onRefresh();               //子类扩展  
    32.   
    33.                 // Check for listener beans and register them.  
    34.                 registerListeners();   //注册监听器  
    35.   
    36.                 // Instantiate all remaining (non-lazy-init) singletons.  
    37.                 finishBeanFactoryInitialization(beanFactory);   //实例化非延迟加载单例,包括所有注册非延迟加载bean的实例化  
    38.   
    39.                 // Last step: publish corresponding event.  
    40.                 finishRefresh();     //完成刷新过程,通知生命周期处理器lifecycleProcessor刷新过程,同时发出ContextRefreshEvent通知别人  
    41.             }  
    42.   
    43.             catch (BeansException ex) {  
    44.                 if (logger.isWarnEnabled()) {  
    45.                     logger.warn("Exception encountered during context initialization - " +  
    46.                             "cancelling refresh attempt: " + ex);  
    47.                 }  
    48.   
    49.                 // Destroy already created singletons to avoid dangling resources.  
    50.                 destroyBeans();  
    51.   
    52.                 // Reset 'active' flag.  
    53.                 cancelRefresh(ex);  
    54.   
    55.                 // Propagate exception to caller.  
    56.                 throw ex;  
    57.             }  
    58.   
    59.             finally {  
    60.                 // Reset common introspection caches in Spring's core, since we  
    61.                 // might not ever need metadata for singleton beans anymore...  
    62.                 resetCommonCaches();  
    63.             }  
    64.         }  
    65.     }  

    从上述代码看,注解处理器也是在registerBeanPostProcessors(beanFactory);中进行实例化的:
    1. public static void registerBeanPostProcessors(  
    2.             ConfigurableListableBeanFactory beanFactory, AbstractApplicationContext applicationContext) {  
    3.                 //获取所有beanFactory注册的BeanPostProcessor类型的bean处理器,三中注册的bean处理器在这里都会获取到  
    4.         String[] postProcessorNames = beanFactory.getBeanNamesForType(BeanPostProcessor.class, true, false);  
    5.   
    6.         // Register BeanPostProcessorChecker that logs an info message when  
    7.         // a bean is created during BeanPostProcessor instantiation, i.e. when  
    8.         // a bean is not eligible for getting processed by all BeanPostProcessors.  
    9.         int beanProcessorTargetCount = beanFactory.getBeanPostProcessorCount() + 1 + postProcessorNames.length;  
    10.         beanFactory.addBeanPostProcessor(new BeanPostProcessorChecker(beanFactory, beanProcessorTargetCount));  
    11.                 //以下是实例化bean处理器,并按照次序或无序添加到BeanFactory的beanPostProcessors列表中  
    12.         // Separate between BeanPostProcessors that implement PriorityOrdered,  
    13.         // Ordered, and the rest.  
    14.         List<BeanPostProcessor> priorityOrderedPostProcessors = new ArrayList<BeanPostProcessor>();  
    15.         List<BeanPostProcessor> internalPostProcessors = new ArrayList<BeanPostProcessor>();  
    16.         List<String> orderedPostProcessorNames = new ArrayList<String>();  
    17.         List<String> nonOrderedPostProcessorNames = new ArrayList<String>();  
    18.         for (String ppName : postProcessorNames) {  
    19.             if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {  
    20.                 BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);  
    21.                 priorityOrderedPostProcessors.add(pp);  
    22.                 if (pp instanceof MergedBeanDefinitionPostProcessor) {  
    23.                     internalPostProcessors.add(pp);  
    24.                 }  
    25.             }  
    26.             else if (beanFactory.isTypeMatch(ppName, Ordered.class)) {  
    27.                 orderedPostProcessorNames.add(ppName);  
    28.             }  
    29.             else {  
    30.                 nonOrderedPostProcessorNames.add(ppName);  
    31.             }  
    32.         }  
    33.   
    34.         // First, register the BeanPostProcessors that implement PriorityOrdered.  
    35.         sortPostProcessors(beanFactory, priorityOrderedPostProcessors);  
    36.         registerBeanPostProcessors(beanFactory, priorityOrderedPostProcessors);  
    37.   
    38.         // Next, register the BeanPostProcessors that implement Ordered.  
    39.         List<BeanPostProcessor> orderedPostProcessors = new ArrayList<BeanPostProcessor>();  
    40.         for (String ppName : orderedPostProcessorNames) {  
    41.             BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);  
    42.             orderedPostProcessors.add(pp);  
    43.             if (pp instanceof MergedBeanDefinitionPostProcessor) {  
    44.                 internalPostProcessors.add(pp);  
    45.             }  
    46.         }  
    47.         sortPostProcessors(beanFactory, orderedPostProcessors);  
    48.         registerBeanPostProcessors(beanFactory, orderedPostProcessors);  
    49.   
    50.         // Now, register all regular BeanPostProcessors.  
    51.         List<BeanPostProcessor> nonOrderedPostProcessors = new ArrayList<BeanPostProcessor>();  
    52.         for (String ppName : nonOrderedPostProcessorNames) {  
    53.             BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);  
    54.             nonOrderedPostProcessors.add(pp);  
    55.             if (pp instanceof MergedBeanDefinitionPostProcessor) {  
    56.                 internalPostProcessors.add(pp);  
    57.             }  
    58.         }  
    59.         registerBeanPostProcessors(beanFactory, nonOrderedPostProcessors);  
    60.   
    61.         // Finally, re-register all internal BeanPostProcessors.  
    62.         sortPostProcessors(beanFactory, internalPostProcessors);  
    63.         registerBeanPostProcessors(beanFactory, internalPostProcessors);  
    64.   
    65.         beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(applicationContext));  
    66.     }  
    上述代码实现了bean处理器实例化和排序工作,最终通过registerBeanPostProcessors添加到BeanFactory的beanPostProcessors列表中。

    1. /** 
    2.      * Register the given BeanPostProcessor beans. 
    3.      */  
    4.     private static void registerBeanPostProcessors(  
    5.             ConfigurableListableBeanFactory beanFactory, List<BeanPostProcessor> postProcessors) {  
    6.   
    7.         for (BeanPostProcessor postProcessor : postProcessors) {  
    8.             beanFactory.addBeanPostProcessor(postProcessor);  
    9.         }  
    10.     }  
    AbstractBeanFactory.java
    1. @Override  
    2.     public void addBeanPostProcessor(BeanPostProcessor beanPostProcessor) {  
    3.         Assert.notNull(beanPostProcessor, "BeanPostProcessor must not be null");  
    4.         this.beanPostProcessors.remove(beanPostProcessor);  
    5.         this.beanPostProcessors.add(beanPostProcessor);  
    6.         if (beanPostProcessor instanceof InstantiationAwareBeanPostProcessor) {  
    7.             this.hasInstantiationAwareBeanPostProcessors = true;  
    8.         }  
    9.         if (beanPostProcessor instanceof DestructionAwareBeanPostProcessor) {  
    10.             this.hasDestructionAwareBeanPostProcessors = true;  
    11.         }  
    12.     }  
    这里的beanPostProcessors在应用bean实例化的时候会进行调用。bean处理器的实例化这里不细说,也是通过beanFactory.getBean()实现的。


    五、注解处理器的调用

    【Spring实战】Spring容器初始化完成后执行初始化数据方法中的注解@PostConstruct为例分析其注解处理器的调用。四种分析了处理器的实例化,看一下@postConstruct处理器CommonAnnotationBeanPostProcessor.java,其构造函数如下:
    1. /** 
    2.      * Create a new CommonAnnotationBeanPostProcessor, 
    3.      * with the init and destroy annotation types set to 
    4.      * {@link javax.annotation.PostConstruct} and {@link javax.annotation.PreDestroy}, 
    5.      * respectively. 
    6.      */  
    7.     public CommonAnnotationBeanPostProcessor() {  
    8.         setOrder(Ordered.LOWEST_PRECEDENCE - 3);  
    9.         setInitAnnotationType(PostConstruct.class);  
    10.         setDestroyAnnotationType(PreDestroy.class);  
    11.         ignoreResourceType("javax.xml.ws.WebServiceContext");  
    12.     }  
    其中设置了初始化注解类型PostConstruct。下面看下这个注解处理器是在哪调用的,那就是创建bean,初始化bean时。创建bean的大概包括以下几步(在这里不做代码分析):
    1)创建bean实例,也就是bean的实例化,其实例化策略并不是简单的使用反射方法直接反射来构造实例对象的,而是反射方法和动态代理(主要针对aop)相结合的方式。
    2)记录创建bean的objectFactory
    3)属性注入
    4)初始化bean
    5)注册disposablebean
    附上spring bean的生命周期
     
    其中@PostConstruct处理器的调用就是在初始化bean时调用的,而属性的注解,如@Autowired处理器是在属性注入的时候调用的。先看下调用栈
     
    @PostConstuct的
    1. at com.mango.jtt.init.InitMango.init(InitMango.java:29)  
    2.       at sun.reflect.NativeMethodAccessorImpl.invoke0(NativeMethodAccessorImpl.java:-1)  
    3.       at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)  
    4.       at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)  
    5.       at java.lang.reflect.Method.invoke(Method.java:498)  
    6.       at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor$LifecycleElement.invoke(InitDestroyAnnotationBeanPostProcessor.java:365)  
    7.       at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor$LifecycleMetadata.invokeInitMethods(InitDestroyAnnotationBeanPostProcessor.java:310)  
    8.       at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor.postProcessBeforeInitialization(InitDestroyAnnotationBeanPostProcessor.java:133)  
    9.       at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyBeanPostProcessorsBeforeInitialization(AbstractAutowireCapableBeanFactory.java:408)  
    10.       at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1570)  
    11.       at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:545)  
    12.       at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)  
    13.       at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)  
    14.       at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)  
    15.       - locked <0xe68> (a java.util.concurrent.ConcurrentHashMap)  
    16.       at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)  
    17.       at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)  
    18.       at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:776)  
    19.       at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:861)  
    20.       at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:541)  
    21.       - locked <0x19af> (a java.lang.Object)  
    22.       at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:444)  
    23.       at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:326)  
    24.       at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:107)  

    @Autowired处理器的调用栈
    1. at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:347)  
    2.       at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1214)  
    3.       at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:543)  
    4.       at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)  
    5.       at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)  
    6.       at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)  
    7.       - locked <0xe4f> (a java.util.concurrent.ConcurrentHashMap)  
    8.       at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)  
    9.       at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202)  
    10.       at org.springframework.context.support.PostProcessorRegistrationDelegate.registerBeanPostProcessors(PostProcessorRegistrationDelegate.java:228)  
    11.       at org.springframework.context.support.AbstractApplicationContext.registerBeanPostProcessors(AbstractApplicationContext.java:697)  
    12.       at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:526)  
    13.       - locked <0xe50> (a java.lang.Object)  
    14.       at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:444)  
    15.       at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:326)  
    16.       at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:107)  
     
    具体分析下@PostConstruct的注解处理器调用

    1. /** 
    2.      * Actually create the specified bean. Pre-creation processing has already happened 
    3.      * at this point, e.g. checking {@code postProcessBeforeInstantiation} callbacks. 
    4.      * <p>Differentiates between default bean instantiation, use of a 
    5.      * factory method, and autowiring a constructor. 
    6.      * @param beanName the name of the bean 
    7.      * @param mbd the merged bean definition for the bean 
    8.      * @param args explicit arguments to use for constructor or factory method invocation 
    9.      * @return a new instance of the bean 
    10.      * @throws BeanCreationException if the bean could not be created 
    11.      * @see #instantiateBean 
    12.      * @see #instantiateUsingFactoryMethod 
    13.      * @see #autowireConstructor 
    14.      */  
    15.     protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final Object[] args) {  
    16.         // Instantiate the bean.  
    17.         BeanWrapper instanceWrapper = null;  
    18.         if (mbd.isSingleton()) {  
    19.             instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);  
    20.         }  
    21.         if (instanceWrapper == null) {  
    22.             instanceWrapper = createBeanInstance(beanName, mbd, args);  
    23.         }  
    24.         final Object bean = (instanceWrapper != null ? instanceWrapper.getWrappedInstance() : null);  
    25.         Class<?> beanType = (instanceWrapper != null ? instanceWrapper.getWrappedClass() : null);  
    26.   
    27.         // Allow post-processors to modify the merged bean definition.  
    28.         synchronized (mbd.postProcessingLock) {  
    29.             if (!mbd.postProcessed) {  
    30.                 applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);  
    31.                 mbd.postProcessed = true;  
    32.             }  
    33.         }  
    34.   
    35.         // Eagerly cache singletons to be able to resolve circular references  
    36.         // even when triggered by lifecycle interfaces like BeanFactoryAware.  
    37.         boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences &&  
    38.                 isSingletonCurrentlyInCreation(beanName));  
    39.         if (earlySingletonExposure) {  
    40.             if (logger.isDebugEnabled()) {  
    41.                 logger.debug("Eagerly caching bean '" + beanName +  
    42.                         "' to allow for resolving potential circular references");  
    43.             }  
    44.             addSingletonFactory(beanName, new ObjectFactory<Object>() {  
    45.                 @Override  
    46.                 public Object getObject() throws BeansException {  
    47.                     return getEarlyBeanReference(beanName, mbd, bean);  
    48.                 }  
    49.             });  
    50.         }  
    51.   
    52.         // Initialize the bean instance.  
    53.         Object exposedObject = bean;  
    54.         try {  
    55.             populateBean(beanName, mbd, instanceWrapper);  
    56.             if (exposedObject != null) {  
    57.                 exposedObject = initializeBean(beanName, exposedObject, mbd);  
    58.             }  
    59.         }  
    60.         catch (Throwable ex) {  
    61.             if (ex instanceof BeanCreationException && beanName.equals(((BeanCreationException) ex).getBeanName())) {  
    62.                 throw (BeanCreationException) ex;  
    63.             }  
    64.             else {  
    65.                 throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Initialization of bean failed", ex);  
    66.             }  
    67.         }  
    68.   
    69.         if (earlySingletonExposure) {  
    70.             Object earlySingletonReference = getSingleton(beanName, false);  
    71.             if (earlySingletonReference != null) {  
    72.                 if (exposedObject == bean) {  
    73.                     exposedObject = earlySingletonReference;  
    74.                 }  
    75.                 else if (!this.allowRawInjectionDespiteWrapping && hasDependentBean(beanName)) {  
    76.                     String[] dependentBeans = getDependentBeans(beanName);  
    77.                     Set<String> actualDependentBeans = new LinkedHashSet<String>(dependentBeans.length);  
    78.                     for (String dependentBean : dependentBeans) {  
    79.                         if (!removeSingletonIfCreatedForTypeCheckOnly(dependentBean)) {  
    80.                             actualDependentBeans.add(dependentBean);  
    81.                         }  
    82.                     }  
    83.                     if (!actualDependentBeans.isEmpty()) {  
    84.                         throw new BeanCurrentlyInCreationException(beanName,  
    85.                                 "Bean with name '" + beanName + "' has been injected into other beans [" +  
    86.                                 StringUtils.collectionToCommaDelimitedString(actualDependentBeans) +  
    87.                                 "] in its raw version as part of a circular reference, but has eventually been " +  
    88.                                 "wrapped. This means that said other beans do not use the final version of the " +  
    89.                                 "bean. This is often the result of over-eager type matching - consider using " +  
    90.                                 "'getBeanNamesOfType' with the 'allowEagerInit' flag turned off, for example.");  
    91.                     }  
    92.                 }  
    93.             }  
    94.         }  
    95.   
    96.         // Register bean as disposable.  
    97.         try {  
    98.             registerDisposableBeanIfNecessary(beanName, bean, mbd);  
    99.         }  
    100.         catch (BeanDefinitionValidationException ex) {  
    101.             throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Invalid destruction signature", ex);  
    102.         }  
    103.   
    104.         return exposedObject;  
    105.     }  
    上述代码包含了创建bean的所有步骤,直接看下bean的初始化initializeBean
     
    1. /** 
    2.      * Initialize the given bean instance, applying factory callbacks 
    3.      * as well as init methods and bean post processors. 
    4.      * <p>Called from {@link #createBean} for traditionally defined beans, 
    5.      * and from {@link #initializeBean} for existing bean instances. 
    6.      * @param beanName the bean name in the factory (for debugging purposes) 
    7.      * @param bean the new bean instance we may need to initialize 
    8.      * @param mbd the bean definition that the bean was created with 
    9.      * (can also be {@code null}, if given an existing bean instance) 
    10.      * @return the initialized bean instance (potentially wrapped) 
    11.      * @see BeanNameAware 
    12.      * @see BeanClassLoaderAware 
    13.      * @see BeanFactoryAware 
    14.      * @see #applyBeanPostProcessorsBeforeInitialization 
    15.      * @see #invokeInitMethods 
    16.      * @see #applyBeanPostProcessorsAfterInitialization 
    17.      */  
    18.     protected Object initializeBean(final String beanName, final Object bean, RootBeanDefinition mbd) {  
    19.         if (System.getSecurityManager() != null) {  
    20.             AccessController.doPrivileged(new PrivilegedAction<Object>() {  
    21.                 @Override  
    22.                 public Object run() {  
    23.                     invokeAwareMethods(beanName, bean);  
    24.                     return null;  
    25.                 }  
    26.             }, getAccessControlContext());  
    27.         }  
    28.         else {  
    29.             invokeAwareMethods(beanName, bean);  
    30.         }  
    31.   
    32.         Object wrappedBean = bean;  
    33.         if (mbd == null || !mbd.isSynthetic()) {  
    34.             wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);  
    35.         }  
    36.   
    37.         try {  
    38.             invokeInitMethods(beanName, wrappedBean, mbd);  
    39.         }  
    40.         catch (Throwable ex) {  
    41.             throw new BeanCreationException(  
    42.                     (mbd != null ? mbd.getResourceDescription() : null),  
    43.                     beanName, "Invocation of init method failed", ex);  
    44.         }  
    45.   
    46.         if (mbd == null || !mbd.isSynthetic()) {  
    47.             wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);  
    48.         }  
    49.         return wrappedBean;  
    50.     }  

    初始化给定的bean实例,应用工厂回调以及init方法和bean post处理器。顺便说一句,实现了InitializingBean接口的bean的afterPropertiseSet()方法是在
    invokeInitMethods(beanName, wrappedBean, mbd);中进行调用的。接着看
    1. @Override  
    2.     public Object applyBeanPostProcessorsBeforeInitialization(Object existingBean, String beanName)  
    3.             throws BeansException {  
    4.   
    5.         Object result = existingBean;  
    6.         for (BeanPostProcessor beanProcessor : getBeanPostProcessors()) {  
    7.             result = beanProcessor.postProcessBeforeInitialization(result, beanName);  
    8.             if (result == null) {  
    9.                 return result;  
    10.             }  
    11.         }  
    12.         return result;  
    13.     }  

    这里就用到了前面注册的beanPostProcessors列表,于是就调用到了CommonAnnotationBeanPostProcessor中的postProcessBeforeInitialization()方法(继承自InitDestroyAnnotationBeanPostProcessor.java)
     
    1. @Override  
    2.     public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {  
    3.         LifecycleMetadata metadata = findLifecycleMetadata(bean.getClass());  
    4.         try {  
    5.             metadata.invokeInitMethods(bean, beanName);  
    6.         }  
    7.         catch (InvocationTargetException ex) {  
    8.             throw new BeanCreationException(beanName, "Invocation of init method failed", ex.getTargetException());  
    9.         }  
    10.         catch (Throwable ex) {  
    11.             throw new BeanCreationException(beanName, "Failed to invoke init method", ex);  
    12.         }  
    13.         return bean;  
    14.     }  

    上述代码也很简单,就是获取用@PostConstruct注解标注的method,然后调用,看下findLifecycleMetadata实现
    1. private LifecycleMetadata buildLifecycleMetadata(final Class<?> clazz) {  
    2.         final boolean debug = logger.isDebugEnabled();  
    3.         LinkedList<LifecycleElement> initMethods = new LinkedList<LifecycleElement>();  
    4.         LinkedList<LifecycleElement> destroyMethods = new LinkedList<LifecycleElement>();  
    5.         Class<?> targetClass = clazz;  
    6.   
    7.         do {  
    8.             final LinkedList<LifecycleElement> currInitMethods = new LinkedList<LifecycleElement>();  
    9.             final LinkedList<LifecycleElement> currDestroyMethods = new LinkedList<LifecycleElement>();  
    10.   
    11.             ReflectionUtils.doWithLocalMethods(targetClass, new ReflectionUtils.MethodCallback() {  
    12.                 @Override  
    13.                 public void doWith(Method method) throws IllegalArgumentException, IllegalAccessException {  
    14.                     if (initAnnotationType != null) {  
    15.                         if (method.getAnnotation(initAnnotationType) != null) {  
    16.                             LifecycleElement element = new LifecycleElement(method);  
    17.                             currInitMethods.add(element);  
    18.                             if (debug) {  
    19.                                 logger.debug("Found init method on class [" + clazz.getName() + "]: " + method);  
    20.                             }  
    21.                         }  
    22.                     }  
    23.                     if (destroyAnnotationType != null) {  
    24.                         if (method.getAnnotation(destroyAnnotationType) != null) {  
    25.                             currDestroyMethods.add(new LifecycleElement(method));  
    26.                             if (debug) {  
    27.                                 logger.debug("Found destroy method on class [" + clazz.getName() + "]: " + method);  
    28.                             }  
    29.                         }  
    30.                     }  
    31.                 }  
    32.             });  
    33.   
    34.             initMethods.addAll(0, currInitMethods);  
    35.             destroyMethods.addAll(currDestroyMethods);  
    36.             targetClass = targetClass.getSuperclass();  
    37.         }  
    38.         while (targetClass != null && targetClass != Object.class);  
    39.   
    40.         return new LifecycleMetadata(clazz, initMethods, destroyMethods);  
    41.     }  

    是不是有种豁然开朗的感觉。
     
    1. public void invokeInitMethods(Object target, String beanName) throws Throwable {  
    2.             Collection<LifecycleElement> initMethodsToIterate =  
    3.                     (this.checkedInitMethods != null ? this.checkedInitMethods : this.initMethods);  
    4.             if (!initMethodsToIterate.isEmpty()) {  
    5.                 boolean debug = logger.isDebugEnabled();  
    6.                 for (LifecycleElement element : initMethodsToIterate) {  
    7.                     if (debug) {  
    8.                         logger.debug("Invoking init method on bean '" + beanName + "': " + element.getMethod());  
    9.                     }  
    10.                     element.invoke(target);  
    11.                 }  
    12.             }  
    13.         }  

    1. public void invoke(Object target) throws Throwable {  
    2.             ReflectionUtils.makeAccessible(this.method);  
    3.             this.method.invoke(target, (Object[]) null);  
    4.         }  

    熟悉的java反射。至此整个Spring注解的工作原理就分析完了,总结如下:
     
    1)利用asm技术扫描class文件,转化成Spring bean结构,把符合扫描规则的(主要是是否有相关的注解标注,例如@Component)bean注册到Spring 容器中beanFactory
    2)注册处理器,包括注解处理器
    4)实例化处理器(包括注解处理器),并将其注册到容器的beanPostProcessors列表中
    5)创建bean的过程中个,属性注入或者初始化bean时会调用对应的注解处理器进行处理
     
     
    转自:http://blog.csdn.net/honghailiang888/article/details/74981445
  • 相关阅读:
    Linux三阶段之十一:keepalived高可用集群
    Linux三阶段之十:nginx反向代理负载均衡
    Linux三阶段之九:期中架构LNMP章节
    【Linux面试题7】三剑客笔试题集合
    【Linux面试题6】定时任务
    【Linux面试题5】文件编辑和查找类
    【Linux面试题4】用户管理
    【Linux面试题3】磁盘管理
    【Linux面试题2】目录结构及相关命令
    【Linux面试题1】服务器硬件与基础命令
  • 原文地址:https://www.cnblogs.com/caogen1991/p/7911857.html
Copyright © 2020-2023  润新知