百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 技术资源 > 正文

Spring中@Configuration注解原理_@configuration注解 springboot

moboyou 2025-09-29 07:36 10 浏览

之前在《关于@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技巧:SHEETSNA函数一键提取所有工作表名称批量生产目录

首先介绍一下此函数:SHEETSNAME函数用于获取工作表的名称,有三个可选参数。语法:=SHEETSNAME([参照区域],[结果方向],[工作表范围])(参照区域,可选。给出参照,只返回参照单元格...

Excel HOUR函数:“小时”提取器_excel+hour函数提取器怎么用

一、函数概述HOUR函数是Excel中用于提取时间值小时部分的日期时间函数,返回0(12:00AM)到23(11:00PM)之间的整数。该函数在时间数据分析、考勤统计、日程安排等场景中应用广泛。语...

Filter+Search信息管理不再难|多条件|模糊查找|Excel函数应用

原创版权所有介绍一个信息管理系统,要求可以实现:多条件、模糊查找,手动输入的内容能去空格。先看效果,如下图动画演示这样的一个效果要怎样实现呢?本文所用函数有Filter和Search。先用filter...

FILTER函数介绍及经典用法12:FILTER+切片器的应用

EXCEL函数技巧:FILTER经典用法12。FILTER+切片器制作筛选按钮。FILTER的函数的经典用法12是用FILTER的函数和切片器制作一个筛选按钮。像左边的原始数据,右边想要制作一...

office办公应用网站推荐_office办公软件大全

以下是针对Office办公应用(Word/Excel/PPT等)的免费学习网站推荐,涵盖官方教程、综合平台及垂直领域资源,适合不同学习需求:一、官方权威资源1.微软Office官方培训...

WPS/Excel职场办公最常用的60个函数大全(含卡片),效率翻倍!

办公最常用的60个函数大全:从入门到精通,效率翻倍!在职场中,WPS/Excel几乎是每个人都离不开的工具,而函数则是其灵魂。掌握常用的函数,不仅能大幅提升工作效率,还能让你在数据处理、报表分析、自动...

收藏|查找神器Xlookup全集|一篇就够|Excel函数|图解教程

原创版权所有全程图解,方便阅读,内容比较多,请先收藏!Xlookup是Vlookup的升级函数,解决了Vlookup的所有缺点,可以完全取代Vlookup,学完本文后你将可以应对所有的查找难题,内容...

批量查询快递总耗时?用Excel这个公式,自动计算揽收到签收天数

批量查询快递总耗时?用Excel这个公式,自动计算揽收到签收天数在电商运营、物流对账等工作中,经常需要统计快递“揽收到签收”的耗时——比如判断某快递公司是否符合“3天内送达”的服务承...

Excel函数公式教程(490个实例详解)

Excel函数公式教程(490个实例详解)管理层的财务人员为什么那么厉害?就是因为他们精通excel技能!财务人员在日常工作中,经常会用到Excel财务函数公式,比如财务报表分析、工资核算、库存管理等...

Excel(WPS表格)Tocol函数应用技巧案例解读,建议收藏备用!

工作中,经常需要从多个单元格区域中提取唯一值,如体育赛事报名信息中提取唯一的参赛者信息等,此时如果复制粘贴然后去重,效率就会很低。如果能合理利用Tocol函数,将会极大地提高工作效率。一、功能及语法结...

Excel中的SCAN函数公式,把计算过程理清,你就会了

Excel新版本里面,除了出现非常好用的xlookup,Filter公式之外,还更新一批自定义函数,可以像写代码一样写公式其中SCAN函数公式,也非常强大,它是一个循环函数,今天来了解这个函数公式的计...

Excel(WPS表格)中多列去重就用Tocol+Unique组合函数,简单高效

在数据的分析和处理中,“去重”一直是绕不开的话题,如果单列去重,可以使用Unique函数完成,如果多列去重,如下图:从数据信息中可以看到,每位参赛者参加了多项运动,如果想知道去重后的参赛者有多少人,该...

Excel(WPS表格)函数Groupby,聚合统计,快速提高效率!

在前期的内容中,我们讲了很多的统计函数,如Sum系列、Average系列、Count系列、Rank系列等等……但如果用一个函数实现类似数据透视表的功能,就必须用Groupby函数,按指定字段进行聚合汇...

Excel新版本,IFS函数公式,太强大了!

我们举一个工作实例,现在需要计算业务员的奖励数据,右边是公司的奖励标准:在新版本的函数公式出来之前,我们需要使用IF函数公式来解决1、IF函数公式IF函数公式由三个参数组成,IF(判断条件,对的时候返...

Excel不用函数公式数据透视表,1秒完成多列项目汇总统计

如何将这里的多组数据进行汇总统计?每组数据当中一列是不同菜品,另一列就是该菜品的销售数量。如何进行汇总统计得到所有的菜品销售数量的求和、技术、平均、最大、最小值等数据?不用函数公式和数据透视表,一秒就...