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

相关文章

Java实战之利用POI生成Excel图表

《Java实战之利用POI生成Excel图表》ApachePOI是Java生态中处理Office文档的核心工具,这篇文章主要为大家详细介绍了如何在Excel中创建折线图,柱状图,饼图等常见图表,需要的... 目录一、环境配置与依赖管理二、数据源准备与工作表构建三、图表生成核心步骤1. 折线图(Line Ch

Spring Boot 3 整合 Spring Cloud Gateway实践过程

《SpringBoot3整合SpringCloudGateway实践过程》本文介绍了如何使用SpringCloudAlibaba2023.0.0.0版本构建一个微服务网关,包括统一路由、限... 目录引子为什么需要微服务网关实践1.统一路由2.限流防刷3.登录鉴权小结引子当前微服务架构已成为中大型系统的标

Java集合中的List超详细讲解

《Java集合中的List超详细讲解》本文详细介绍了Java集合框架中的List接口,包括其在集合中的位置、继承体系、常用操作和代码示例,以及不同实现类(如ArrayList、LinkedList和V... 目录一,List的继承体系二,List的常用操作及代码示例1,创建List实例2,增加元素3,访问元

Java中将异步调用转为同步的五种实现方法

《Java中将异步调用转为同步的五种实现方法》本文介绍了将异步调用转为同步阻塞模式的五种方法:wait/notify、ReentrantLock+Condition、Future、CountDownL... 目录异步与同步的核心区别方法一:使用wait/notify + synchronized代码示例关键

MobaXterm远程登录工具功能与应用小结

《MobaXterm远程登录工具功能与应用小结》MobaXterm是一款功能强大的远程终端软件,主要支持SSH登录,拥有多种远程协议,实现跨平台访问,它包括多会话管理、本地命令行执行、图形化界面集成和... 目录1. 远程终端软件概述1.1 远程终端软件的定义与用途1.2 远程终端软件的关键特性2. 支持的

Java 8 Stream filter流式过滤器详解

《Java8Streamfilter流式过滤器详解》本文介绍了Java8的StreamAPI中的filter方法,展示了如何使用lambda表达式根据条件过滤流式数据,通过实际代码示例,展示了f... 目录引言 一.Java 8 Stream 的过滤器(filter)二.Java 8 的 filter、fi

Java中实现订单超时自动取消功能(最新推荐)

《Java中实现订单超时自动取消功能(最新推荐)》本文介绍了Java中实现订单超时自动取消功能的几种方法,包括定时任务、JDK延迟队列、Redis过期监听、Redisson分布式延迟队列、Rocket... 目录1、定时任务2、JDK延迟队列 DelayQueue(1)定义实现Delayed接口的实体类 (

springboot的调度服务与异步服务使用详解

《springboot的调度服务与异步服务使用详解》本文主要介绍了Java的ScheduledExecutorService接口和SpringBoot中如何使用调度线程池,包括核心参数、创建方式、自定... 目录1.调度服务1.1.JDK之ScheduledExecutorService1.2.spring

将java程序打包成可执行文件的实现方式

《将java程序打包成可执行文件的实现方式》本文介绍了将Java程序打包成可执行文件的三种方法:手动打包(将编译后的代码及JRE运行环境一起打包),使用第三方打包工具(如Launch4j)和JDK自带... 目录1.问题提出2.如何将Java程序打包成可执行文件2.1将编译后的代码及jre运行环境一起打包2

Java使用Tesseract-OCR实战教程

《Java使用Tesseract-OCR实战教程》本文介绍了如何在Java中使用Tesseract-OCR进行文本提取,包括Tesseract-OCR的安装、中文训练库的配置、依赖库的引入以及具体的代... 目录Java使用Tesseract-OCRTesseract-OCR安装配置中文训练库引入依赖代码实