一道经典面试题:@Configuration 和 @Component 有何区别?

一道经典面试题:@Configuration 和 @Component 有何区别?

💡 原文中文,约13200字,阅读约需32分钟。
📝

内容提要

介绍Spring中@Configuration注解的Full模式和Lite模式的处理方式,以及动态代理增强配置类的方法。通过源码分析讲解增强类中的setCallbackFilter方法和BeanMethodInterceptor拦截器的作用,以及避免Full模式下@Bean注解标记的方法重复创建Bean。

🎯

关键要点

  • @Configuration 和 @Component 的区别在于前者注册到 Spring 容器中的 Bean 是 CGLIB 代理的 Bean,而后者是原始 Bean。
  • @Configuration 注解的处理分为 Full 模式和 Lite 模式,使用 ConfigurationClassPostProcessor 进行处理。
  • Full 模式的配置类需要 @Configuration 注解且 proxyBeanMethods 属性不为 false,Lite 模式则相反。
  • postProcessBeanDefinitionRegistry 方法用于判断配置类的模式,并标记 BeanDefinition。
  • postProcessBeanFactory 方法通过 CGLIB 动态代理增强配置类,以便处理 Bean 请求。
  • 增强类中的 setCallbackFilter 方法包含多个方法拦截器,BeanMethodInterceptor 是关键拦截器。
  • 在 Full 模式下,调用 @Bean 注解标记的方法不会导致 Bean 的重复创建,使用了拦截方法进行处理。
➡️

继续阅读