spring小结(6)-细看@Configuration的appconfig代理类

2023-10-13 15:59

本文主要是介绍spring小结(6)-细看@Configuration的appconfig代理类,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

之前提过@Configuration的appconfig会被cglib代理,生存代理类,然后是对象,在进行含有@Bean方法调用进项1拦截,

这里需要细看详细的代理类和拦截细节,为了看是一次调用 new,还是getbean,,(isCurrentlyInvokedFactoryMethod(beanMethod)) 起了重要作用

 * 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 {ConfigurableBeanFactory beanFactory = getBeanFactory(enhancedConfigInstance);String beanName = BeanAnnotationHelper.determineBeanNameFor(beanMethod);// Determine whether this bean is a scoped-proxyScope scope = AnnotatedElementUtils.findMergedAnnotation(beanMethod, Scope.class);if (scope != null && scope.proxyMode() != ScopedProxyMode.NO) {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 enhancementreturn 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.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);}return resolveBeanReference(beanMethod, beanMethodArgs, beanFactory, beanName);
}

细看,此方法是判断当前调用方法中是否是执行的方法

private boolean isCurrentlyInvokedFactoryMethod(Method method) {Method currentlyInvoked = SimpleInstantiationStrategy.getCurrentlyInvokedFactoryMethod();return (currentlyInvoked != null && method.getName().equals(currentlyInvoked.getName()) &&Arrays.equals(method.getParameterTypes(), currentlyInvoked.getParameterTypes()));
}

例子解释

public class lmqDao {public lmqDao(){System.out.println("lmqdao1-init");}public void print(){System.out.println("lmqdao - print ------");}
}
  public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {System.out.println("method ----");return methodProxy.invokeSuper(o,objects);}
}
@Configuration
@ComponentScan("com.lmq.BaseService")
//@Import(MyImportBeanDefinitionRegistrar.class)
@Import(MyImportSelector.class)
public class AppConfig {@Beanpublic    lmqDao indexdao(){return new lmqDao();}@Beanpublic lmqDao1 indexdao1(){indexdao();//没有@configuration会输出2次,在加了@configuration,只会输出1遍“lmqdao-init",因为被cglib代理,只会创建一个lmqdao,构造函数也就输出一次return new lmqDao1();  }

''''''''''''''''''''''''''

当只调外层的indexdao()时,Method method=MethodProxy methodProxy,即代理方法=调用方法,

当调用indexdao1(),由于其内部调用了indexdao(),此时Method method=indexdao(),MethodProxy methodProxy是indexdao1(),

假设启动,第一次时,方法一样,

此时,后面执行父类,

return cglibMethodProxy.invokeSuper(enhancedConfigInstance, beanMethodArgs)

同理调用indedao1()(还未执行到indexdao1中的indexdao()时)一样,

查看后续执行,同样直接返回父类,

但当执行到indexdao1()中的indexdao()调用时,如下图就不一样了,

后面的流程也不一样,本质从被cglib代理的appconfig对象从beanfactory 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;}}}Object beanInstance = (useArgs ? beanFactory.getBean(beanName, beanMethodArgs) :beanFactory.getBean(beanName));if (!ClassUtils.isAssignableValue(beanMethod.getReturnType(), beanInstance)) {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;}

如下图可以拿到已创建的beaninstance,就不用new了,实现了拦截,

 

至此,invokeBeanFactoryPostProcessors(beanFactory);大部分执行完毕

ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();// Prepare the bean factory for use in this context.
prepareBeanFactory(beanFactory);try {// Allows post-processing of the bean factory in context subclasses.postProcessBeanFactory(beanFactory);// Invoke factory processors registered as beans in the context.invokeBeanFactoryPostProcessors(beanFactory);// Register bean processors that intercept bean creation.registerBeanPostProcessors(beanFactory);// Initialize message source for this context.initMessageSource();// Initialize event multicaster for this context.initApplicationEventMult

这篇关于spring小结(6)-细看@Configuration的appconfig代理类的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/204337

相关文章

Spring Boot 实现 IP 限流的原理、实践与利弊解析

《SpringBoot实现IP限流的原理、实践与利弊解析》在SpringBoot中实现IP限流是一种简单而有效的方式来保障系统的稳定性和可用性,本文给大家介绍SpringBoot实现IP限... 目录一、引言二、IP 限流原理2.1 令牌桶算法2.2 漏桶算法三、使用场景3.1 防止恶意攻击3.2 控制资源

Mac系统下卸载JAVA和JDK的步骤

《Mac系统下卸载JAVA和JDK的步骤》JDK是Java语言的软件开发工具包,它提供了开发和运行Java应用程序所需的工具、库和资源,:本文主要介绍Mac系统下卸载JAVA和JDK的相关资料,需... 目录1. 卸载系统自带的 Java 版本检查当前 Java 版本通过命令卸载系统 Java2. 卸载自定

springboot下载接口限速功能实现

《springboot下载接口限速功能实现》通过Redis统计并发数动态调整每个用户带宽,核心逻辑为每秒读取并发送限定数据量,防止单用户占用过多资源,确保整体下载均衡且高效,本文给大家介绍spring... 目录 一、整体目标 二、涉及的主要类/方法✅ 三、核心流程图解(简化) 四、关键代码详解1️⃣ 设置

Java Spring ApplicationEvent 代码示例解析

《JavaSpringApplicationEvent代码示例解析》本文解析了Spring事件机制,涵盖核心概念(发布-订阅/观察者模式)、代码实现(事件定义、发布、监听)及高级应用(异步处理、... 目录一、Spring 事件机制核心概念1. 事件驱动架构模型2. 核心组件二、代码示例解析1. 事件定义

SpringMVC高效获取JavaBean对象指南

《SpringMVC高效获取JavaBean对象指南》SpringMVC通过数据绑定自动将请求参数映射到JavaBean,支持表单、URL及JSON数据,需用@ModelAttribute、@Requ... 目录Spring MVC 获取 JavaBean 对象指南核心机制:数据绑定实现步骤1. 定义 Ja

javax.net.ssl.SSLHandshakeException:异常原因及解决方案

《javax.net.ssl.SSLHandshakeException:异常原因及解决方案》javax.net.ssl.SSLHandshakeException是一个SSL握手异常,通常在建立SS... 目录报错原因在程序中绕过服务器的安全验证注意点最后多说一句报错原因一般出现这种问题是因为目标服务器

Python打印对象所有属性和值的方法小结

《Python打印对象所有属性和值的方法小结》在Python开发过程中,调试代码时经常需要查看对象的当前状态,也就是对象的所有属性和对应的值,然而,Python并没有像PHP的print_r那样直接提... 目录python中打印对象所有属性和值的方法实现步骤1. 使用vars()和pprint()2. 使

HTML5 getUserMedia API网页录音实现指南示例小结

《HTML5getUserMediaAPI网页录音实现指南示例小结》本教程将指导你如何利用这一API,结合WebAudioAPI,实现网页录音功能,从获取音频流到处理和保存录音,整个过程将逐步... 目录1. html5 getUserMedia API简介1.1 API概念与历史1.2 功能与优势1.3

Java实现删除文件中的指定内容

《Java实现删除文件中的指定内容》在日常开发中,经常需要对文本文件进行批量处理,其中,删除文件中指定内容是最常见的需求之一,下面我们就来看看如何使用java实现删除文件中的指定内容吧... 目录1. 项目背景详细介绍2. 项目需求详细介绍2.1 功能需求2.2 非功能需求3. 相关技术详细介绍3.1 Ja

springboot项目中整合高德地图的实践

《springboot项目中整合高德地图的实践》:本文主要介绍springboot项目中整合高德地图的实践,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录一:高德开放平台的使用二:创建数据库(我是用的是mysql)三:Springboot所需的依赖(根据你的需求再