Spring中@Configuration注解修改的类生成代理原因解析

 更新时间:2022年02月08日 11:34:36   作者:码拉松  
大家好,本篇文章主要讲的是Spring中@Configuration注解修改的类生成代理原因解析,感兴趣的同学赶快来看一看吧,对你有帮助的话记得收藏一下

前言

在Spring中只要被@Configuration注解修饰的类,Spring就会为其生成代理对象,至于这样做的主要原因就是为了解决生成对象的单例问题。

说明

实际上作者在ConfigurationClassEnhancer这个类也有注解说明

在这里插入图片描述

场景

如果Spring不做处理,下面输出的一定的是false,但是实际上输出的结果是true,那么只有可能是代理类做了特殊处理。

@Configuration
public class MyConfiguration {
    @Bean
    public TestA a(){
        return new TestA();
    }
    @Bean
    public TestB b(){
        TestA a = a();
        TestA b = a();
        System.out.println(a == b);
        return new TestB();
    }
}

处理分析

生成的代理对象,最终会调用ConfigurationClassEnhancer内部类BeanMethodInterceptor的intercept方法,如果不是当前调用的Bean对象(也就是isCurrentlyInvokedFactoryMethod(beanMethod)返回false),则会调用resolveBeanReference方法。

public Object intercept(Object enhancedConfigInstance, Method beanMethod, Object[] beanMethodArgs,
			MethodProxy cglibMethodProxy) throws Throwable {
	ConfigurableBeanFactory beanFactory = getBeanFactory(enhancedConfigInstance);
	String beanName = BeanAnnotationHelper.determineBeanNameFor(beanMethod);
	// Determine whether this bean is a scoped-proxy
	if (BeanAnnotationHelper.isScopedProxy(beanMethod)) {
		String scopedBeanName = ScopedProxyCreator.getTargetBeanName(beanName);
		if (beanFactory.isCurrentlyInCreation(scopedBeanName)) {
			beanName = scopedBeanName;
		}
	}
	// To handle the case of an inter-bean method reference, we must explicitly check the
	// container for already cached instances.
	// First, check to see if the requested bean is a FactoryBean. If so, create a subclass
	// proxy that intercepts calls to getObject() and returns any cached bean instance.
	// This ensures that the semantics of calling a FactoryBean from within @Bean methods
	// is the same as that of referring to a FactoryBean within XML. See SPR-6602.
	if (factoryContainsBean(beanFactory, BeanFactory.FACTORY_BEAN_PREFIX + beanName) &&
			factoryContainsBean(beanFactory, beanName)) {
		Object factoryBean = beanFactory.getBean(BeanFactory.FACTORY_BEAN_PREFIX + beanName);
		if (factoryBean instanceof ScopedProxyFactoryBean) {
			// Scoped proxy factory beans are a special case and should not be further proxied
		}
		else {
			// It is a candidate FactoryBean - go ahead with enhancement
			return enhanceFactoryBean(factoryBean, beanMethod.getReturnType(), beanFactory, beanName);
		}
	}
	if (isCurrentlyInvokedFactoryMethod(beanMethod)) {
		// The factory is calling the bean method in order to instantiate and register the bean
		// (i.e. via a getBean() call) -> invoke the super implementation of the method to actually
		// create the bean instance.
		if (logger.isInfoEnabled() &&
				BeanFactoryPostProcessor.class.isAssignableFrom(beanMethod.getReturnType())) {
			logger.info(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);
	}
	return resolveBeanReference(beanMethod, beanMethodArgs, beanFactory, beanName);
}

此方法会通过getBean来获取对象,这样就可以控制对象的生成了。

private Object resolveBeanReference(Method beanMethod, Object[] beanMethodArgs,
		ConfigurableBeanFactory beanFactory, String beanName) {
	// The user (i.e. not the factory) is requesting this bean through a call to
	// the bean method, direct or indirect. The bean may have already been marked
	// as 'in creation' in certain autowiring scenarios; if so, temporarily set
	// the in-creation status to false in order to avoid an exception.
	boolean alreadyInCreation = beanFactory.isCurrentlyInCreation(beanName);
	try {
		if (alreadyInCreation) {
			beanFactory.setCurrentlyInCreation(beanName, false);
		}
		boolean useArgs = !ObjectUtils.isEmpty(beanMethodArgs);
		if (useArgs && beanFactory.isSingleton(beanName)) {
			// Stubbed null arguments just for reference purposes,
			// expecting them to be autowired for regular singleton references?
			// A safe assumption since @Bean singleton arguments cannot be optional...
			for (Object arg : beanMethodArgs) {
				if (arg == null) {
					useArgs = false;
					break;
				}
			}
		}
		// 通过getBean就可以控制对象的生成,对象如果生成过,则可以直接从一级缓存中获取
		Object beanInstance = (useArgs ? beanFactory.getBean(beanName, beanMethodArgs) :
				beanFactory.getBean(beanName));
		if (!ClassUtils.isAssignableValue(beanMethod.getReturnType(), beanInstance)) {
			// Detect package-protected NullBean instance through equals(null) check
			if (beanInstance.equals(null)) {
				if (logger.isDebugEnabled()) {
					logger.debug(String.format("@Bean method %s.%s called as bean reference " +
							"for type [%s] returned null bean; resolving to null value.",
							beanMethod.getDeclaringClass().getSimpleName(), beanMethod.getName(),
							beanMethod.getReturnType().getName()));
				}
				beanInstance = null;
			}
			else {
				String msg = String.format("@Bean method %s.%s called as bean reference " +
						"for type [%s] but overridden by non-compatible bean instance of type [%s].",
						beanMethod.getDeclaringClass().getSimpleName(), beanMethod.getName(),
						beanMethod.getReturnType().getName(), beanInstance.getClass().getName());
				try {
					BeanDefinition beanDefinition = beanFactory.getMergedBeanDefinition(beanName);
					msg += " Overriding bean of same name declared in: " + beanDefinition.getResourceDescription();
				}
				catch (NoSuchBeanDefinitionException ex) {
					// Ignore - simply no detailed message then.
				}
				throw new IllegalStateException(msg);
			}
		}
		Method currentlyInvoked = SimpleInstantiationStrategy.getCurrentlyInvokedFactoryMethod();
		if (currentlyInvoked != null) {
			String outerBeanName = BeanAnnotationHelper.determineBeanNameFor(currentlyInvoked);
			beanFactory.registerDependentBean(beanName, outerBeanName);
		}
		return beanInstance;
	}
	finally {
		if (alreadyInCreation) {
			beanFactory.setCurrentlyInCreation(beanName, true);
		}
	}
}

总结

到此这篇关于Spring中@Configuration注解修改的类生成代理原因解析的文章就介绍到这了,更多相关Spring @Configuration注解内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • Java中守护线程介绍及使用

    Java中守护线程介绍及使用

    大家好,本篇文章主要讲的是Java中守护线程介绍及使用,感兴趣的同学赶快来看一看吧,对你有帮助的话记得收藏一下
    2022-01-01
  • springmvc前台向后台传值几种方式总结(从简单到复杂)

    springmvc前台向后台传值几种方式总结(从简单到复杂)

    今天小编就为大家分享一篇springmvc前台向后台传值几种方式总结(从简单到复杂),具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2018-08-08
  • Java中字符序列的替换与分解的几种实现方法

    Java中字符序列的替换与分解的几种实现方法

    本文主要介绍了Java中字符序列的替换与分解的几种实现方法,文中通过示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2022-02-02
  • IDEA报错:java 找不到符号图文解决过程

    IDEA报错:java 找不到符号图文解决过程

    这篇文章主要给大家介绍了关于IDEA报错:java 找不到符号解决的相关资料,运行项目时Idea报错,提示找不到符号,但是这个类在项目里是存在的,网上找了很多文章都没解决,浪费了一个下午终于弄好了,记录一下,需要的朋友可以参考下
    2023-08-08
  • mybatis-plus使用问题小结

    mybatis-plus使用问题小结

    这篇文章主要介绍了mybatis-plus使用问题汇总,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2022-03-03
  • ElasticSearch整合SpringBoot搭建配置

    ElasticSearch整合SpringBoot搭建配置

    这篇文章主要为大家介绍了ElasticSearch整合SpringBoot搭建配置详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2023-02-02
  • javaweb实现在线支付功能

    javaweb实现在线支付功能

    这篇文章主要为大家详细介绍了javaweb实现在线支付功能的相关资料,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2016-11-11
  • 如何使用BufferedReader循环读文件

    如何使用BufferedReader循环读文件

    这篇文章主要介绍了如何使用BufferedReader循环读文件的操作,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2021-07-07
  • 使用IDEA打jar包的详细图文教程

    使用IDEA打jar包的详细图文教程

    JAR文件是一种压缩文件,与常见的ZIP压缩文件兼容,被称为JAR包,下面这篇文章主要给大家介绍了关于使用IDEA打jar包的相关资料,文中通过图文介绍的非常详细,需要的朋友可以参考下
    2022-08-08
  • 使用spring框架中的组件发送邮件功能说明

    使用spring框架中的组件发送邮件功能说明

    Spring使用的是基本的JavaBean来完成以前只可能由EJB完成的事情。这篇文章主要介绍了使用spring框架中的组件发送邮件,需要的朋友可以参考下
    2017-11-11

最新评论