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

本文内容纲要:

- 一、背景知识

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

- 三、context:component-scan标签解析

- 四、注解处理器实例化

- 五、注解处理器的调用

一、背景知识

在【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发现机制和自动装配)的使用是这样建议的:

Image

如果要使用自动配置机制,就要在配置文件中配置context:component-scan标签或者在配置类中添加@ComponentScan注解。基于【Spring实战】----Spring配置文件的解析

篇文章,本文还是基于xml中的自定义标签进行解析,当然也可以直接看@ComponentScan注解的解析(ComponentScanAnnotationParser.java,这其中还牵扯到@Configuration以及另外的知识点)。

三、context:component-scan标签解析

以实战篇系列demo为例进行分析

[java] view plaincopy

  1. <context:component-scan base-package="com.mango.jtt"></context:component-scan>

从【Spring实战】----Spring配置文件的解析中可知,标签的处理器为spring.handlers

[html] view plaincopy

  1. http\://www.springframework.org/schema/context=org.springframework.context.config.ContextNamespaceHandler

[java] view plaincopy

  1. registerBeanDefinitionParser("component-scan", new ComponentScanBeanDefinitionParser());

在ComponentScanBeanDefinitionParser.java中进行处理

[java] view plaincopy

  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. // Actually scan for bean definitions and register them.
  8. ClassPathBeanDefinitionScanner scanner = configureScanner(parserContext, element); //得到扫描器
  9. Set beanDefinitions = scanner.doScan(basePackages); //扫描文件,并转化为spring bean,并注册
  10. registerComponents(parserContext.getReaderContext(), beanDefinitions, element); //注册其他相关组件
  11. return null;
  12. }

从上述代码中可知,其作用就是扫描basePackages下的文件,转化为spring中的bean结构,并将其注册到容器中;最后是注册相关组件(主要是注解处理器)。注解需要注解处理器来处理。

要知道ComponentScanBeanDefinitionParser扫描文件并转化成spring bean的原则的,就需要看下其定义的属性值:

[java] view plaincopy

  1. private static final String BASE_PACKAGE_ATTRIBUTE = "base-package";
  2. private static final String RESOURCE_PATTERN_ATTRIBUTE = "resource-pattern";
  3. private static final String USE_DEFAULT_FILTERS_ATTRIBUTE = "use-default-filters";
  4. private static final String ANNOTATION_CONFIG_ATTRIBUTE = "annotation-config";
  5. private static final String NAME_GENERATOR_ATTRIBUTE = "name-generator";
  6. private static final String SCOPE_RESOLVER_ATTRIBUTE = "scope-resolver";
  7. private static final String SCOPED_PROXY_ATTRIBUTE = "scoped-proxy";
  8. private static final String EXCLUDE_FILTER_ELEMENT = "exclude-filter";
  9. private static final String INCLUDE_FILTER_ELEMENT = "include-filter";
  10. private static final String FILTER_TYPE_ATTRIBUTE = "type";
  11. private static final String FILTER_EXPRESSION_ATTRIBUTE = "expression";

先简单解析下上述属性的作用

  • base-package:为必须配置属性,指定了spring需要扫描的跟目录名称,可以使用”,” “;” “\t\n(回车符)”来分割多个包名

  • resource-pattern:配置扫描资源格式.默认”**/*.class

  • use-default-filters:是否使用默认扫描策略,默认为”true”,会自动扫描指定包下的添加了如下注解的类,@Component, @Repository, @Service,or @Controller

  • Image

  • 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()函数中进行的。

[java] view plaincopy

  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. // Delegate bean definition registration to scanner class.
  7. ClassPathBeanDefinitionScanner scanner = createScanner(parserContext.getReaderContext(), useDefaultFilters); //包含了扫描策略配置
  8. scanner.setResourceLoader(parserContext.getReaderContext().getResourceLoader());
  9. scanner.setEnvironment(parserContext.getReaderContext().getEnvironment());
  10. scanner.setBeanDefinitionDefaults(parserContext.getDelegate().getBeanDefinitionDefaults());
  11. scanner.setAutowireCandidatePatterns(parserContext.getDelegate().getAutowireCandidatePatterns());
  12. if (element.hasAttribute(RESOURCE_PATTERN_ATTRIBUTE)) {
  13. scanner.setResourcePattern(element.getAttribute(RESOURCE_PATTERN_ATTRIBUTE)); //配置扫描资源格式
  14. }
  15. try {
  16. parseBeanNameGenerator(element, scanner); //配置名称生成器
  17. }
  18. catch (Exception ex) {
  19. parserContext.getReaderContext().error(ex.getMessage(), parserContext.extractSource(element), ex.getCause());
  20. }
  21. try {
  22. parseScope(element, scanner); //配置元数据解析器
  23. }
  24. catch (Exception ex) {
  25. parserContext.getReaderContext().error(ex.getMessage(), parserContext.extractSource(element), ex.getCause());
  26. }
  27. parseTypeFilters(element, scanner, parserContext); //配置包含和不包含过滤
  28. return scanner;
  29. }

看一下默认扫描策略的配置

[java] view plaincopy

  1. /**
  2. * Register the default filter for {@link Component @Component}.
  3. *

    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. *

    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

[java] view plaincopy

  1. /**
  2. * Perform a scan within the specified base packages,
  3. * returning the registered bean definitions.
  4. *

    This method does not 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 doScan(String... basePackages) {
  10. Assert.notEmpty(basePackages, "At least one base package must be specified");
  11. Set beanDefinitions = new LinkedHashSet();
  12. for (String basePackage : basePackages) {
  13. Set 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来做的

[java] view plaincopy

  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 findCandidateComponents(String basePackage) {
  7. Set candidates = new LinkedHashSet();
  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结构

[java] view plaincopy

  1. MetadataReader metadataReader = this.metadataReaderFactory.getMetadataReader(resource);

[java] view plaincopy

  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. AnnotationMetadataReadingVisitor visitor = new AnnotationMetadataReadingVisitor(classLoader);
  15. classReader.accept(visitor, ClassReader.SKIP_DEBUG);
  16. this.annotationMetadata = visitor;
  17. // (since AnnotationMetadataReadingVisitor extends ClassMetadataReadingVisitor)
  18. this.classMetadata = visitor;
  19. this.resource = resource;
  20. }

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

[java] view plaincopy

  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. }

先看第一个判断

[java] view plaincopy

  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就是判断类是否是实现类,抽象类好接口类都不不可以

[java] view plaincopy

  1. /**
  2. * Determine whether the given bean definition qualifies as candidate.
  3. *

    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中

[java] view plaincopy

  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

[java] view plaincopy

  1. registerComponents(parserContext.getReaderContext(), beanDefinitions, element);

[java] view plaincopy

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

上述代码的作用主要是注册注解处理器,本例中没有配置annotation-config,默认值为true,这里也就说明了为什么配置了context:component-scan标签就不需要再配置context:annotation-config标签的原因。看下注册注解处理器:

org.springframework.context.annotation.AnnotationConfigUtils.java

[java] view plaincopy

  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 registerAnnotationConfigProcessors(
  10. BeanDefinitionRegistry registry, Object source) {
  11. DefaultListableBeanFactory beanFactory = unwrapDefaultListableBeanFactory(registry);
  12. if (beanFactory != null) {
  13. if (!(beanFactory.getDependencyComparator() instanceof AnnotationAwareOrderComparator)) {
  14. beanFactory.setDependencyComparator(AnnotationAwareOrderComparator.INSTANCE); //设置注解比较器,为Spring中的Order提供支持
  15. }
  16. if (!(beanFactory.getAutowireCandidateResolver() instanceof ContextAnnotationAutowireCandidateResolver)) {
  17. beanFactory.setAutowireCandidateResolver(new ContextAnnotationAutowireCandidateResolver()); //设置AutowireCandidateResolver,为qualifier注解和lazy注解提供支持
  18. }
  19. }
  20. Set beanDefs = new LinkedHashSet(4);
  21. if (!registry.containsBeanDefinition(CONFIGURATION_ANNOTATION_PROCESSOR_BEAN_NAME)) {
  22. RootBeanDefinition def = new RootBeanDefinition(ConfigurationClassPostProcessor.class);
  23. def.setSource(source);
  24. beanDefs.add(registerPostProcessor(registry, def, CONFIGURATION_ANNOTATION_PROCESSOR_BEAN_NAME)); //注册@Configuration处理器
  25. }
  26. if (!registry.containsBeanDefinition(AUTOWIRED_ANNOTATION_PROCESSOR_BEAN_NAME)) {
  27. RootBeanDefinition def = new RootBeanDefinition(AutowiredAnnotationBeanPostProcessor.class);
  28. def.setSource(source);
  29. beanDefs.add(registerPostProcessor(registry, def, AUTOWIRED_ANNOTATION_PROCESSOR_BEAN_NAME));//注册@Autowired、@Value、@Inject处理器
  30. }
  31. if (!registry.containsBeanDefinition(REQUIRED_ANNOTATION_PROCESSOR_BEAN_NAME)) {
  32. RootBeanDefinition def = new RootBeanDefinition(RequiredAnnotationBeanPostProcessor.class);
  33. def.setSource(source);
  34. beanDefs.add(registerPostProcessor(registry, def, REQUIRED_ANNOTATION_PROCESSOR_BEAN_NAME));//注册@Required处理器
  35. }
  36. // Check for JSR-250 support, and if present add the CommonAnnotationBeanPostProcessor.
  37. if (jsr250Present && !registry.containsBeanDefinition(COMMON_ANNOTATION_PROCESSOR_BEAN_NAME)) {
  38. RootBeanDefinition def = new RootBeanDefinition(CommonAnnotationBeanPostProcessor.class);
  39. def.setSource(source);
  40. beanDefs.add(registerPostProcessor(registry, def, COMMON_ANNOTATION_PROCESSOR_BEAN_NAME));//在支持JSR-250条件下注册javax.annotation包下注解处理器,包括@PostConstruct、@PreDestroy、@Resource注解等
  41. }
  42. // Check for JPA support, and if present add the PersistenceAnnotationBeanPostProcessor.
  43. if (jpaPresent && !registry.containsBeanDefinition(PERSISTENCE_ANNOTATION_PROCESSOR_BEAN_NAME)) {
  44. RootBeanDefinition def = new RootBeanDefinition();
  45. try {
  46. def.setBeanClass(ClassUtils.forName(PERSISTENCE_ANNOTATION_PROCESSOR_CLASS_NAME,
  47. AnnotationConfigUtils.class.getClassLoader()));
  48. }
  49. catch (ClassNotFoundException ex) {
  50. throw new IllegalStateException(
  51. "Cannot load optional framework class: " + PERSISTENCE_ANNOTATION_PROCESSOR_CLASS_NAME, ex);
  52. }
  53. def.setSource(source);
  54. beanDefs.add(registerPostProcessor(registry, def, PERSISTENCE_ANNOTATION_PROCESSOR_BEAN_NAME));//支持jpa的条件下,注册org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor处理器,处理jpa相关注解
  55. }
  56. if (!registry.containsBeanDefinition(EVENT_LISTENER_PROCESSOR_BEAN_NAME)) {
  57. RootBeanDefinition def = new RootBeanDefinition(EventListenerMethodProcessor.class);
  58. def.setSource(source);
  59. beanDefs.add(registerPostProcessor(registry, def, EVENT_LISTENER_PROCESSOR_BEAN_NAME));//注册@EventListener处理器
  60. }
  61. if (!registry.containsBeanDefinition(EVENT_LISTENER_FACTORY_BEAN_NAME)) {
  62. RootBeanDefinition def = new RootBeanDefinition(DefaultEventListenerFactory.class);
  63. def.setSource(source);
  64. beanDefs.add(registerPostProcessor(registry, def, EVENT_LISTENER_FACTORY_BEAN_NAME));//注册支持@EventListener注解的处理器
  65. }
  66. return beanDefs;
  67. }

真正的注册是如下函数:

[java] view plaincopy

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

注册注解处理器的过程也是讲处理包装成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()函数

[java] view plaincopy

  1. @Override
  2. public void refresh() throws BeansException, IllegalStateException {
  3. synchronized (this.startupShutdownMonitor) {
  4. // Prepare this context for refreshing.
  5. prepareRefresh(); //初始化前的准备,例如对系统属性或者环境变量进行准备及验证
  6. // Tell the subclass to refresh the internal bean factory.
  7. ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory(); //初始化BeanFactory,解析xml配置文件,其中标签context:component-scan就是在这里解析的
  8. // Prepare the bean factory for use in this context.
  9. prepareBeanFactory(beanFactory); //配置工厂的标准上下文特征,例如上下文的类加载器和后处理器。
  10. try {
  11. // Allows post-processing of the bean factory in context subclasses.
  12. postProcessBeanFactory(beanFactory); //子类覆盖方法,做特殊处理,主要是后处理器相关
  13. // Invoke factory processors registered as beans in the context.
  14. invokeBeanFactoryPostProcessors(beanFactory); //激活各种beanFactory处理器,实例化并调用所有注册的BeanFactoryPostProcessor bean,
  15. 如果给定的话,尊重显式的顺序。注意这里和扫描时的bean处理器的区别。
  16. // Register bean processors that intercept bean creation.
  17. 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 style="color: rgb(46, 48, 51); font-family: Arial, "Microsoft YaHei", 微软雅黑, 宋体, "Malgun Gothic", Meiryo, sans-serif; line-height: 18px;">如果给定的话,尊重显式的顺序。<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;">
<span style="color: rgb(46, 48, 51); font-family: Arial, "Microsoft YaHei", 微软雅黑, 宋体, "Malgun Gothic", Meiryo, sans-serif; line-height: 18px;">必须在应用程序bean的任何实例化之前调用它。这是本节的分析重点。这里就是实例化上面注册的bean处理器

  • // Initialize message source for this context.
  • initMessageSource(); //初始化消息资源,国际化等用
  • // Initialize event multicaster for this context.
  • initApplicationEventMulticaster(); //初始化应用事件广播
  • // Initialize other special beans in specific context subclasses.
  • onRefresh(); //子类扩展
  • // Check for listener beans and register them.
  • registerListeners(); //注册监听器
  • // Instantiate all remaining (non-lazy-init) singletons.
  • finishBeanFactoryInitialization(beanFactory); //实例化非延迟加载单例,包括所有注册非延迟加载bean的实例化
  • // Last step: publish corresponding event.
  • finishRefresh(); //完成刷新过程,通知生命周期处理器lifecycleProcessor刷新过程,同时发出ContextRefreshEvent通知别人
  • }
  • catch (BeansException ex) {
  • if (logger.isWarnEnabled()) {
  • logger.warn("Exception encountered during context initialization - " +
  • "cancelling refresh attempt: " + ex);
  • }
  • // Destroy already created singletons to avoid dangling resources.
  • destroyBeans();
  • // Reset 'active' flag.
  • cancelRefresh(ex);
  • // Propagate exception to caller.
  • throw ex;
  • }
  • finally {
  • // Reset common introspection caches in Spring's core, since we
  • // might not ever need metadata for singleton beans anymore...
  • resetCommonCaches();
  • }
  • }
  • }
  • 从上述代码看,注解处理器也是在registerBeanPostProcessors(beanFactory);中进行实例化的:

    [java] view plaincopy

    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. // Register BeanPostProcessorChecker that logs an info message when
    6. // a bean is created during BeanPostProcessor instantiation, i.e. when
    7. // a bean is not eligible for getting processed by all BeanPostProcessors.
    8. int beanProcessorTargetCount = beanFactory.getBeanPostProcessorCount() + 1 + postProcessorNames.length;
    9. beanFactory.addBeanPostProcessor(new BeanPostProcessorChecker(beanFactory, beanProcessorTargetCount));
    10. //以下是实例化bean处理器,并按照次序或无序添加到BeanFactory的beanPostProcessors列表中
    11. // Separate between BeanPostProcessors that implement PriorityOrdered,
    12. // Ordered, and the rest.
    13. List priorityOrderedPostProcessors = new ArrayList();
    14. List internalPostProcessors = new ArrayList();
    15. List orderedPostProcessorNames = new ArrayList();
    16. List nonOrderedPostProcessorNames = new ArrayList();
    17. for (String ppName : postProcessorNames) {
    18. if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
    19. BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
    20. priorityOrderedPostProcessors.add(pp);
    21. if (pp instanceof MergedBeanDefinitionPostProcessor) {
    22. internalPostProcessors.add(pp);
    23. }
    24. }
    25. else if (beanFactory.isTypeMatch(ppName, Ordered.class)) {
    26. orderedPostProcessorNames.add(ppName);
    27. }
    28. else {
    29. nonOrderedPostProcessorNames.add(ppName);
    30. }
    31. }
    32. // First, register the BeanPostProcessors that implement PriorityOrdered.
    33. sortPostProcessors(beanFactory, priorityOrderedPostProcessors);
    34. registerBeanPostProcessors(beanFactory, priorityOrderedPostProcessors);
    35. // Next, register the BeanPostProcessors that implement Ordered.
    36. List orderedPostProcessors = new ArrayList();
    37. for (String ppName : orderedPostProcessorNames) {
    38. BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
    39. orderedPostProcessors.add(pp);
    40. if (pp instanceof MergedBeanDefinitionPostProcessor) {
    41. internalPostProcessors.add(pp);
    42. }
    43. }
    44. sortPostProcessors(beanFactory, orderedPostProcessors);
    45. registerBeanPostProcessors(beanFactory, orderedPostProcessors);
    46. // Now, register all regular BeanPostProcessors.
    47. List nonOrderedPostProcessors = new ArrayList();
    48. for (String ppName : nonOrderedPostProcessorNames) {
    49. BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
    50. nonOrderedPostProcessors.add(pp);
    51. if (pp instanceof MergedBeanDefinitionPostProcessor) {
    52. internalPostProcessors.add(pp);
    53. }
    54. }
    55. registerBeanPostProcessors(beanFactory, nonOrderedPostProcessors);
    56. // Finally, re-register all internal BeanPostProcessors.
    57. sortPostProcessors(beanFactory, internalPostProcessors);
    58. registerBeanPostProcessors(beanFactory, internalPostProcessors);
    59. beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(applicationContext));
    60. }

    上述代码实现了bean处理器实例化和排序工作,最终通过registerBeanPostProcessors添加到BeanFactory的beanPostProcessors列表中。

    [java] view plaincopy

    1. /**
    2. * Register the given BeanPostProcessor beans.
    3. */
    4. private static void registerBeanPostProcessors(
    5. ConfigurableListableBeanFactory beanFactory, List postProcessors) {
    6. for (BeanPostProcessor postProcessor : postProcessors) {
    7. beanFactory.addBeanPostProcessor(postProcessor);
    8. }
    9. }

    AbstractBeanFactory.java

    [java] view plaincopy

    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,其构造函数如下:

    [java] view plaincopy

    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的生命周期

    Image

    其中@PostConstruct处理器的调用就是在初始化bean时调用的,而属性的注解,如@Autowired处理器是在属性注入的时候调用的。先看下调用栈

    @PostConstuct的

    [java] view plaincopy

    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处理器的调用栈

    [java] view plaincopy

    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的注解处理器调用

    [java] view plaincopy

    1. /**
    2. * Actually create the specified bean. Pre-creation processing has already happened
    3. * at this point, e.g. checking {@code postProcessBeforeInstantiation} callbacks.
    4. *

      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. // Allow post-processors to modify the merged bean definition.
    27. synchronized (mbd.postProcessingLock) {
    28. if (!mbd.postProcessed) {
    29. applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);
    30. mbd.postProcessed = true;
    31. }
    32. }
    33. // Eagerly cache singletons to be able to resolve circular references
    34. // even when triggered by lifecycle interfaces like BeanFactoryAware.
    35. boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences &&
    36. isSingletonCurrentlyInCreation(beanName));
    37. if (earlySingletonExposure) {
    38. if (logger.isDebugEnabled()) {
    39. logger.debug("Eagerly caching bean '" + beanName +
    40. "' to allow for resolving potential circular references");
    41. }
    42. addSingletonFactory(beanName, new ObjectFactory() {
    43. @Override
    44. public Object getObject() throws BeansException {
    45. return getEarlyBeanReference(beanName, mbd, bean);
    46. }
    47. });
    48. }
    49. // Initialize the bean instance.
    50. Object exposedObject = bean;
    51. try {
    52. populateBean(beanName, mbd, instanceWrapper);
    53. if (exposedObject != null) {
    54. exposedObject = initializeBean(beanName, exposedObject, mbd);
    55. }
    56. }
    57. catch (Throwable ex) {
    58. if (ex instanceof BeanCreationException && beanName.equals(((BeanCreationException) ex).getBeanName())) {
    59. throw (BeanCreationException) ex;
    60. }
    61. else {
    62. throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Initialization of bean failed", ex);
    63. }
    64. }
    65. if (earlySingletonExposure) {
    66. Object earlySingletonReference = getSingleton(beanName, false);
    67. if (earlySingletonReference != null) {
    68. if (exposedObject == bean) {
    69. exposedObject = earlySingletonReference;
    70. }
    71. else if (!this.allowRawInjectionDespiteWrapping && hasDependentBean(beanName)) {
    72. String[] dependentBeans = getDependentBeans(beanName);
    73. Set actualDependentBeans = new LinkedHashSet(dependentBeans.length);
    74. for (String dependentBean : dependentBeans) {
    75. if (!removeSingletonIfCreatedForTypeCheckOnly(dependentBean)) {
    76. actualDependentBeans.add(dependentBean);
    77. }
    78. }
    79. if (!actualDependentBeans.isEmpty()) {
    80. throw new BeanCurrentlyInCreationException(beanName,
    81. "Bean with name '" + beanName + "' has been injected into other beans [" +
    82. StringUtils.collectionToCommaDelimitedString(actualDependentBeans) +
    83. "] in its raw version as part of a circular reference, but has eventually been " +
    84. "wrapped. This means that said other beans do not use the final version of the " +
    85. "bean. This is often the result of over-eager type matching - consider using " +
    86. "'getBeanNamesOfType' with the 'allowEagerInit' flag turned off, for example.");
    87. }
    88. }
    89. }
    90. }
    91. // Register bean as disposable.
    92. try {
    93. registerDisposableBeanIfNecessary(beanName, bean, mbd);
    94. }
    95. catch (BeanDefinitionValidationException ex) {
    96. throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Invalid destruction signature", ex);
    97. }
    98. return exposedObject;
    99. }

    上述代码包含了创建bean的所有步骤,直接看下bean的初始化initializeBean

    [java] view plaincopy

    1. /**
    2. * Initialize the given bean instance, applying factory callbacks
    3. * as well as init methods and bean post processors.
    4. *

      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() {
    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. Object wrappedBean = bean;
    32. if (mbd == null || !mbd.isSynthetic()) {
    33. wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
    34. }
    35. try {
    36. invokeInitMethods(beanName, wrappedBean, mbd);
    37. }
    38. catch (Throwable ex) {
    39. throw new BeanCreationException(
    40. (mbd != null ? mbd.getResourceDescription() : null),
    41. beanName, "Invocation of init method failed", ex);
    42. }
    43. if (mbd == null || !mbd.isSynthetic()) {
    44. wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
    45. }
    46. return wrappedBean;
    47. }

    初始化给定的bean实例,应用工厂回调以及init方法和bean post处理器。顺便说一句,实现了InitializingBean接口的bean的afterPropertiseSet()方法是在

    invokeInitMethods(beanName, wrappedBean, mbd);中进行调用的。接着看

    [java] view plaincopy

    1. @Override
    2. public Object applyBeanPostProcessorsBeforeInitialization(Object existingBean, String beanName)
    3. throws BeansException {
    4. Object result = existingBean;
    5. for (BeanPostProcessor beanProcessor : getBeanPostProcessors()) {
    6. result = beanProcessor.postProcessBeforeInitialization(result, beanName);
    7. if (result == null) {
    8. return result;
    9. }
    10. }
    11. return result;
    12. }

    这里就用到了前面注册的beanPostProcessors列表,于是就调用到了CommonAnnotationBeanPostProcessor中的postProcessBeforeInitialization()方法(继承自InitDestroyAnnotationBeanPostProcessor.java)

    [java] view plaincopy

    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实现

    [java] view plaincopy

    1. private LifecycleMetadata buildLifecycleMetadata(final Class<?> clazz) {
    2. final boolean debug = logger.isDebugEnabled();
    3. LinkedList initMethods = new LinkedList();
    4. LinkedList destroyMethods = new LinkedList();
    5. Class<?> targetClass = clazz;
    6. do {
    7. final LinkedList currInitMethods = new LinkedList();
    8. final LinkedList currDestroyMethods = new LinkedList();
    9. ReflectionUtils.doWithLocalMethods(targetClass, new ReflectionUtils.MethodCallback() {
    10. @Override
    11. public void doWith(Method method) throws IllegalArgumentException, IllegalAccessException {
    12. if (initAnnotationType != null) {
    13. if (method.getAnnotation(initAnnotationType) != null) {
    14. LifecycleElement element = new LifecycleElement(method);
    15. currInitMethods.add(element);
    16. if (debug) {
    17. logger.debug("Found init method on class [" + clazz.getName() + "]: " + method);
    18. }
    19. }
    20. }
    21. if (destroyAnnotationType != null) {
    22. if (method.getAnnotation(destroyAnnotationType) != null) {
    23. currDestroyMethods.add(new LifecycleElement(method));
    24. if (debug) {
    25. logger.debug("Found destroy method on class [" + clazz.getName() + "]: " + method);
    26. }
    27. }
    28. }
    29. }
    30. });
    31. initMethods.addAll(0, currInitMethods);
    32. destroyMethods.addAll(currDestroyMethods);
    33. targetClass = targetClass.getSuperclass();
    34. }
    35. while (targetClass != null && targetClass != Object.class);
    36. return new LifecycleMetadata(clazz, initMethods, destroyMethods);
    37. }

    是不是有种豁然开朗的感觉。

    [java] view plaincopy

    1. public void invokeInitMethods(Object target, String beanName) throws Throwable {
    2. Collection 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. }

    [java] view plaincopy

    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

    本文内容总结:一、背景知识,二、从context:component-scan标签或@ComponentScan注解说起,三、context:component-scan标签解析,四、注解处理器实例化,五、注解处理器的调用,

    原文链接:https://www.cnblogs.com/caogen1991/p/7911857.html

    以上是 【转】【Spring实战】Spring注解配置工作原理源码解析 的全部内容, 来源链接: utcz.com/z/296400.html

    回到顶部