Spring中@Configuration注解原理_@configuration注解 springboot
moboyou 2025-09-29 07:36 4 浏览
之前在《关于@Bean的full模式和lite模式》一文中写了在@Configuration注解标记的类中使用@Bean注解生成对象和在@Component注解标记的类中使用@Bean注解生成对象的区别,今天来说一下在@Configuration注解标记的类中生成单例Bean的原理。
ConfigurationClassPostProcessor的postProcessBeanFactory
之前说过,使用@Configuration标记的类会被Sping标记成full模式,那具体这个full是什么时候应用的呢?
至于postProcessBeanFactory方法是什么时候被触发的,这里不再赘述。我们直接来看
ConfigurationClassPostProcessor的postProcessBeanFactory
如上图所示,这两个方法的作用是为full模式的类创建代理类,然后使用
ImportAwareBeanPostProcessor后置处理接口在属性注入的时候,为该类注入beanFactory,至于为什么,我们一点一点来看。
enhanceConfigurationClasses:创建代理类
通过下面的代码,我们可以初步理解到,当当前的BeanDefinition是full模式的时候,会被创建代理类。
public void enhanceConfigurationClasses(ConfigurableListableBeanFactory beanFactory) {
Map<String, AbstractBeanDefinition> configBeanDefs = new LinkedHashMap<>();
for (String beanName : beanFactory.getBeanDefinitionNames()) {
BeanDefinition beanDef = beanFactory.getBeanDefinition(beanName);
//判断当前处理的BeanDefinition是否是full模式,是的话,添加到map中
if (ConfigurationClassUtils.isFullConfigurationClass(beanDef)) {
...
configBeanDefs.put(beanName, (AbstractBeanDefinition) beanDef);
}
}
//没有配置类,直接返回
if (configBeanDefs.isEmpty()) {
// nothing to enhance -> return immediately
return;
}
//用于创建代理类
ConfigurationClassEnhancer enhancer = new ConfigurationClassEnhancer();
for (Map.Entry<String, AbstractBeanDefinition> entry : configBeanDefs.entrySet()) {
AbstractBeanDefinition beanDef = entry.getValue();
// If a @Configuration class gets proxied, always proxy the target class
//该属性和自动代理时是相关的
beanDef.setAttribute(AutoProxyUtils.PRESERVE_TARGET_CLASS_ATTRIBUTE, Boolean.TRUE);
try {
// Set enhanced subclass of the user-specified bean class
//Spring是使用CGLIB,而CGLIB是基于继承的方式实现代理,所以这里指定代理类的“父类”类型,也就是当前配置类
Class<?> configClass = beanDef.resolveBeanClass(this.beanClassLoader);
if (configClass != null) {
//开始创建代理类,实际这里返回的就是代理类
Class<?> enhancedClass = enhancer.enhance(configClass, this.beanClassLoader);
//不相等的话,说明创建了代理类,与“父类”不一样
if (configClass != enhancedClass) {
if (logger.isDebugEnabled()) {
logger.debug(String.format("Replacing bean definition '%s' existing class '%s' with " +
"enhanced class '%s'", entry.getKey(), configClass.getName(), enhancedClass.getName()));
}
//设置代理类
beanDef.setBeanClass(enhancedClass);
}
}
}
catch (Throwable ex) {
throw new IllegalStateException("Cannot load configuration class: " + beanDef.getBeanClassName(), ex);
}
}
}
接下来我们来继续深入,看一下enhancer.enhance()是如何创建代理类的
public Class<?> enhance(Class<?> configClass, @Nullable ClassLoader classLoader) {
if (EnhancedConfiguration.class.isAssignableFrom(configClass)) {
...
return configClass;
}
//创建代理类
Class<?> enhancedClass = createClass(newEnhancer(configClass, classLoader));
...
return enhancedClass;
}
private Enhancer newEnhancer(Class<?> superclass, @Nullable ClassLoader classLoader) {
//spring完全复制了一套CGLIB的动态代理,这里使用的是spring的,但是大致都相同
Enhancer enhancer = new Enhancer();
//设置被代理的类为其父类型
enhancer.setSuperclass(superclass);
//让生成的代理类实现EnhancedConfiguration接口(EnhancedConfiguration接口继承了BeanFactoryAware)
enhancer.setInterfaces(new Class<?>[] {EnhancedConfiguration.class});
//设置生成的代理类不实现org.springframework.cglib.proxy.Factory接口
enhancer.setUseFactory(false);
enhancer.setNamingPolicy(SpringNamingPolicy.INSTANCE);
//设置代理类名称的生成策略:Spring定义的一个生成策略:你代理的名称中会有“BySpringCGLIB”字样
//同时给代理类设置一个$beanFactory字段,并设置成BeanFactory类型
enhancer.setStrategy(new BeanFactoryAwareGeneratorStrategy(classLoader));
//这两个是设置拦截器,当目标方法执行的时候进行拦截处理,这里我们下面讲
enhancer.setCallbackFilter(CALLBACK_FILTER);
enhancer.setCallbackTypes(CALLBACK_FILTER.getCallbackTypes());
return enhancer;
}
private Class<?> createClass(Enhancer enhancer) {
//创建代理类
Class<?> subclass = enhancer.createClass();
// Registering callbacks statically (as opposed to thread-local)
// is critical for usage in an OSGi environment (SPR-5932)...
Enhancer.registerStaticCallbacks(subclass, CALLBACKS);
return subclass;
}
BeanFactoryAwareGeneratorStrategy:给代理类设置一个$beanFactory字段,并设置成BeanFactory类型
private static class BeanFactoryAwareGeneratorStrategy extends DefaultGeneratorStrategy {
@Nullable
private final ClassLoader classLoader;
public BeanFactoryAwareGeneratorStrategy(@Nullable ClassLoader classLoader) {
this.classLoader = classLoader;
}
@Override
protected ClassGenerator transform(ClassGenerator cg) throws Exception {
ClassEmitterTransformer transformer = new ClassEmitterTransformer() {
@Override
public void end_class() {
//设置字段
declare_field(Constants.ACC_PUBLIC, BEAN_FACTORY_FIELD, Type.getType(BeanFactory.class), null);
super.end_class();
}
};
return new TransformingClassGenerator(cg, transformer);
}
...
}
这里需要注意一下,我们下面讲的拦截器拦截原理是只有在代理对象实例化后且目标方法执行的时候才会拦截。
CALLBACK_FILTER:代理拦截。在CALLBACK_FILTER中,一共设置了三个拦截器。
private static final Callback[] CALLBACKS = new Callback[] {
new BeanMethodInterceptor(),
new BeanFactoryAwareMethodInterceptor(),
//什么也没做
NoOp.INSTANCE
};
我们重点来看一下代理对象的拦截方法:
BeanFactoryAwareMethodInterceptor和BeanMethodInterceptor
BeanFactoryAwareMethodInterceptor:实现了MethodInterceptor和ConditionalCallback。熟悉CGLIB动态代理的应该知道,当目标方法执行的时候,会调用MethodInterceptor中的intercept方法,而ConditionalCallback则是条件,判断什么条件才会拦截被代理对象然后进行增强。
通过下面代码的理解,我们可以知道,当目标类中有setBeanFactory方法的时候(具体会更复杂,看下面代码注释)才会被拦截,并给这个字段设置beanFactory。
private static class BeanFactoryAwareMethodInterceptor implements MethodInterceptor, ConditionalCallback {
@Override
@Nullable
public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {
//获取代理类中的$beanFactory字段
//这里之所以有这个字段,是因为在BeanFactoryAwareGeneratorStrategy中进行了添加
Field field = ReflectionUtils.findField(obj.getClass(), BEAN_FACTORY_FIELD);
Assert.state(field != null, "Unable to find generated BeanFactory field");
//这是beanFactory对象
field.set(obj, args[0]);
// Does the actual (non-CGLIB) superclass implement BeanFactoryAware?
// If so, call its setBeanFactory() method. If not, just exit.
if (BeanFactoryAware.class.isAssignableFrom(ClassUtils.getUserClass(obj.getClass().getSuperclass()))) {
return proxy.invokeSuper(obj, args);
}
return null;
}
//这里说明一下下面的方法:由于代理类实现了EnhancedConfiguration,而EnhancedConfiguration又继承了BeanFactoryAware
//因此,代理对象在创建对象阶段,会进行属性注入,setBeanFactory()是BeanFactoryAware接口的方法,目的是为了获取beanFactory
//因为,当前方法的作用是为了拦截代理对象中有setBeanFactory()方法的类
@Override
public boolean isMatch(Method candidateMethod) {
//判断当前方法的名字是setBeanFactory,并且setBeanFactory方法的参数只有一个,
//并且这个参数的类型是BeanFactory并且返回声明该方法的类对象。即使方法被子类继承,getDeclaringClass()仍返回最初声明的类
return (candidateMethod.getName().equals("setBeanFactory") &&
candidateMethod.getParameterCount() == 1 &&
BeanFactory.class == candidateMethod.getParameterTypes()[0] &&
BeanFactoryAware.class.isAssignableFrom(candidateMethod.getDeclaringClass()));
}
}
BeanMethodInterceptor:使用@Bean能产生单例Bean的原因。
如果说上面的代码是引入了beanFactory工具,那么下面的代码就是在@Configuration标记的类中使用@Bean注解获取单例Bean的原因了。
但是这个拦截方法的逻辑太多,我们只看关键的部分:
private static class BeanMethodInterceptor implements MethodInterceptor, ConditionalCallback {
/**
* Enhance a {@link Bean @Bean} method to check the supplied BeanFactory for the
* existence of this bean object.
* @throws Throwable as a catch-all for any exception that may be thrown when invoking the
* super implementation of the proxied method i.e., the actual {@code @Bean} method
*/
@Override
@Nullable
public Object intercept(Object enhancedConfigInstance, Method beanMethod, Object[] beanMethodArgs,
MethodProxy cglibMethodProxy) throws Throwable {
//通过反射获取当前代理对象的beanFactory(上面讲述的代码就是说怎么设置的,这里是怎么获取,里面很简单,就是通过反射,不再赘述)
ConfigurableBeanFactory beanFactory = getBeanFactory(enhancedConfigInstance);
String beanName = BeanAnnotationHelper.determineBeanNameFor(beanMethod);
// Determine whether this bean is a scoped-proxy
...
// FactoryBean
...
//isCurrentlyInvokedFactoryMethod很关键
if (isCurrentlyInvokedFactoryMethod(beanMethod)) {
if (logger.isWarnEnabled() &&
BeanFactoryPostProcessor.class.isAssignableFrom(beanMethod.getReturnType())) {
logger.warn(String.format("@Bean method %s.%s is non-static and returns an object " +
"assignable to Spring's BeanFactoryPostProcessor interface. This will " +
"result in a failure to process annotations such as @Autowired, " +
"@Resource and @PostConstruct within the method's declaring " +
"@Configuration class. Add the 'static' modifier to this method to avoid " +
"these container lifecycle issues; see @Bean javadoc for complete details.",
beanMethod.getDeclaringClass().getSimpleName(), beanMethod.getName()));
}
//调用父类的,即代理对象的父类对象的方法,就是我们创建对象的方法
return cglibMethodProxy.invokeSuper(enhancedConfigInstance, beanMethodArgs);
}
//代码太多,简单来说就是通过beanFactory来获取指定的单例bean,而不是再调用我们的方法去创建bean
return resolveBeanReference(beanMethod, beanMethodArgs, beanFactory, beanName);
}
}
private boolean isCurrentlyInvokedFactoryMethod(Method method) {
//获取到当前被调用方法和method被拦截的方法是不是同一个
//这里的理解很重要,我们下面说
Method currentlyInvoked = SimpleInstantiationStrategy.getCurrentlyInvokedFactoryMethod();
//校验method是否和currentlyInvoked为同一个方法
return (currentlyInvoked != null && method.getName().equals(currentlyInvoked.getName()) &&
Arrays.equals(method.getParameterTypes(), currentlyInvoked.getParameterTypes()));
}
//这里怎么理解呢?
//举个例子:在下面的这段代码中,被调用的方法是staff(),
//如果被拦截的方法也是staff()的话,则直接调用代理对象的父类方法,也就是我们的方法
@Bean
public Staff staff() {
return new Staff();
}
@Bean
public String equalsStaff(Staff staff) {
System.out.println("invoke others Bean's INSTANCE is "+staff.hashCode());
//但是在这段代码中,被调用的方法是equalsStaff(),而拦截的方法是staff(),
//这个时候,staff()就不会调用父类的(我们自己的),
//而是通过resolveBeanReference方法从beanFactory中获取,因为
System.out.println("invoke Constructor's INSTANCE is "+staff().hashCode());
return "";
}
因此,上面的类生成的代理类可以简单理解成下面的:
public class StaffConfigProxy extends StaffConfig{
BeanFactory $beanFactory;
void setBeanFactory(BeanFactory beanFactory){
this.$beanFactory=beanFactory;
}
@Bean
public Staff staff() {
return new Staff();
}
@Bean
public String equalsStaff(Staff staff) {
//当前入参的地址值
System.out.println("invoke others Bean's INSTANCE is "+staff.hashCode());
//staff()模拟从容器中获取Bean
System.out.println("invoke Constructor's INSTANCE is "+(Staff)$beanFactory.getBean("staff").hashCode());
return "";
}
}
ImportAwareBeanPostProcessor:属性注入
我们上面说了一大堆,但是都是在BeanDefinition创建阶段做的时候,这个时候还没有进行bean的实例化,也就说明我们讲的拦截方法并没有没调用,真正调用肯定是在bean被实例化的时候。
其实这个
ImportAwareBeanPostProcessor很简单,就是调用EnhancedConfiguration接口的实现类中的setBeanFactory方法设置beanFactory对象,因为EnhancedConfiguration接口继承了BeanFactoryAware接口。
private static class ImportAwareBeanPostProcessor extends InstantiationAwareBeanPostProcessorAdapter {
private final BeanFactory beanFactory;
public ImportAwareBeanPostProcessor(BeanFactory beanFactory) {
this.beanFactory = beanFactory;
}
@Override
public PropertyValues postProcessPropertyValues(
PropertyValues pvs, PropertyDescriptor[] pds, Object bean, String beanName) {
// Inject the BeanFactory before AutowiredAnnotationBeanPostProcessor's
// postProcessPropertyValues method attempts to autowire other configuration beans.
if (bean instanceof EnhancedConfiguration) {
((EnhancedConfiguration) bean).setBeanFactory(this.beanFactory);
}
return pvs;
}
...
}
而
ImportAwareBeanPostProcessor的postProcessPropertyValues执行时机是在bean进行属性注入的时候。
相关推荐
- 高效有趣学Excel:从入门到精通的全面教程分享
-
在当今这个数据驱动的时代,掌握Excel不仅是提升工作效率的利器,更是职场竞争中的一项重要技能。今天,我非常高兴地与大家分享一套全面的Excel学习教程——《高效有趣学Excel:轻松入门到精通》,这...
- Excel新函数重磅来袭!告别复杂公式,效率提升200%!
-
“透视表终于不用点来点去了?”昨晚刷到这条留言,顺手把新表扔进365,一行=GROUPBY(部门,产品,销售额,SUM)回车,三秒出汇总,刷新按钮直接失业。那一刻,办公室空调声都显得多余。有人还在录宏...
- Excel 效率神器:LET 函数入门教程,让复杂公式变简单
-
您是否曾经编写过又长又复杂的Excel公式,然后没过几天自己都看不懂了?或者,同一个计算在公式里重复写了无数次,不仅容易出错,修改起来更是噩梦?Excel推出的LET函数就是来解决这些痛点...
- Excel多对多查询函数新手教程:从案例到实操
-
一、为啥要学多对多查询?举个例子你就懂!假设你是公司HR,手里有张员工技能表(如下),现在需要快速找出:"张三"会哪些技能?"Excel"技能有哪些人掌握?员工姓名...
- 14、VBA代码+excel内置函数,实现高效数据处理(零基础入门)
-
1、学习VBA的主要目的是数据处理,VBA在数据处理上展现出强大的计算实力。它不仅完美继承EXCEl内置函数的功能,还能通过编程语法实现更灵活的应用。无论是基础的加减乘除,还是复杂的统计分析、逻辑判断...
- word和excel零基础学习免费视频教程,赶紧收藏,作者将转付费课
-
亲爱的朋友们:大家好!本人是全国计算机等级考试二级MSoffice高级应用课程的在校授课老师。本人近段时间打算将wore/excel免费分享给所有有需要的朋友。知识本身无深浅,本人知识也有限,如果讲...
- excel函数从入门到精通,5组13个函数,易学易懂易用
-
对于职场中经常使用Excel的小伙伴们,最希望掌握一些函数公式,毕竟给数据处理带来很多方便,可以提高我们的工作效率。今天分享几组函数公式,适合于初学者,也是职场中经常用到的,下次碰到可以直接套用了。0...
- Excel效率神器:LET函数入门教程,让复杂公式变简单
-
写公式写到想砸电脑?教你用LET把Excel公式从“迷宫”变成“小剧本”,几步看懂又好改很多人都经历过这样的窘境:花了半小时写出一条看似厉害的Excel公式,几天后再看自己都懵了,或者同样...
- 完全免费的Excel教程大全,适合日常excel办公和技能提升
-
说明微软官方的excel文档,由于网站在国外,有时打开慢,而且应用层面介绍不够详细;这里介绍一个集齐了excel各种使用方法和说明的网站;网站名称:懒人Excel网站介绍可以看到有基础教程、快捷键、函...
- Excel 新函数 LAMBDA 入门级教程_excel365新增函数
-
LAMBDA函数的出现是Excel历史上的一次革命性飞跃。它允许用户自定义函数,而无需学习VBA等编程语言。这意味着你可以将复杂的、重复的计算逻辑封装成一个简单的、可复用的自定义函数,极大地...
- Excel新函数LAMBDA入门级教程_excel新建函数
-
把复杂公式“变成函数”后,我在Excel上的重复工作少了一半——你也能做到我一直有一个习惯:遇到每天要重复写的复杂公式,就想把它封装起来,像调用内置函数那样去用。说实话,过去没有LAMBDA,这个想法...
- Excel DROP 函数全方位教程:从基础入门到高级动态应用
-
上一篇我们学习了ExcelTAKE函数,今天我们来学习一下和TAKE函数相对应的DROP函数,它是Microsoft365和Excel2021中引入的一个动态数组函数。它的核心功能是从一...
- 学习Excel公式函数还有官方提供的教程,还是免费的!赶紧试试
-
首先声明,这不是广告,纯干货分享!除了学习Excel的基本操作之外,很多人都是冲着公式和函数才去找教程买教材的,这个结论应该不会有什么毛病。因为,Excel的公式函数真的很强大!现在的Excel教程可...
- 什么是保险员常说的“IRR”?让我们一次说明白!
-
买保险的时候,你是不是常听到销售抛出一些术语,比如“IRR很高哦,收益不错!”?听着挺专业,但“IRR”到底啥意思?想问又不好意思问,别急,它其实是个很简单的概念,咱们今天一次把它说明白。1,IRR...
- 理财型保险如何选择缴费期?_理财型保险计算方式
-
选择理财型保险(通常指年金险、增额终身寿险等)的缴费期,并非简单地看哪个年限短或长,而是需要结合自己的财务状况、理财目标和产品特性来综合决定。下面我将为大家详细解析不同缴费期的特点、适用人群和选择策略...
- 一周热门
- 最近发表
-
- 高效有趣学Excel:从入门到精通的全面教程分享
- Excel新函数重磅来袭!告别复杂公式,效率提升200%!
- Excel 效率神器:LET 函数入门教程,让复杂公式变简单
- Excel多对多查询函数新手教程:从案例到实操
- 14、VBA代码+excel内置函数,实现高效数据处理(零基础入门)
- word和excel零基础学习免费视频教程,赶紧收藏,作者将转付费课
- excel函数从入门到精通,5组13个函数,易学易懂易用
- Excel效率神器:LET函数入门教程,让复杂公式变简单
- 完全免费的Excel教程大全,适合日常excel办公和技能提升
- Excel 新函数 LAMBDA 入门级教程_excel365新增函数
- 标签列表
-
- 外键约束 oracle (36)
- oracle的row number (32)
- 唯一索引 oracle (34)
- oracle in 表变量 (28)
- oracle导出dmp导出 (28)
- 多线程的创建方式 (29)
- 多线程 python (30)
- java多线程并发处理 (32)
- 宏程序代码一览表 (35)
- c++需要学多久 (25)
- css class选择器用法 (25)
- css样式引入 (30)
- css教程文字移动 (33)
- php简单源码 (36)
- php个人中心源码 (25)
- php小说爬取源码 (23)
- 云电脑app源码 (22)
- html画折线图 (24)
- docker好玩的应用 (28)
- linux有没有pe工具 (34)
- 可以上传视频的网站源码 (25)
- 随机函数如何生成小数点数字 (31)
- 随机函数excel公式总和不变30个数据随机 (33)
- 所有excel函数公式大全讲解 (22)
- 有动图演示excel函数公式大全讲解 (32)