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

相关文章

JVM 的类初始化机制

前言 当你在 Java 程序中new对象时,有没有考虑过 JVM 是如何把静态的字节码(byte code)转化为运行时对象的呢,这个问题看似简单,但清楚的同学相信也不会太多,这篇文章首先介绍 JVM 类初始化的机制,然后给出几个易出错的实例来分析,帮助大家更好理解这个知识点。 JVM 将字节码转化为运行时对象分为三个阶段,分别是:loading 、Linking、initialization

Spring Security 基于表达式的权限控制

前言 spring security 3.0已经可以使用spring el表达式来控制授权,允许在表达式中使用复杂的布尔逻辑来控制访问的权限。 常见的表达式 Spring Security可用表达式对象的基类是SecurityExpressionRoot。 表达式描述hasRole([role])用户拥有制定的角色时返回true (Spring security默认会带有ROLE_前缀),去

浅析Spring Security认证过程

类图 为了方便理解Spring Security认证流程,特意画了如下的类图,包含相关的核心认证类 概述 核心验证器 AuthenticationManager 该对象提供了认证方法的入口,接收一个Authentiaton对象作为参数; public interface AuthenticationManager {Authentication authenticate(Authenti

Spring Security--Architecture Overview

1 核心组件 这一节主要介绍一些在Spring Security中常见且核心的Java类,它们之间的依赖,构建起了整个框架。想要理解整个架构,最起码得对这些类眼熟。 1.1 SecurityContextHolder SecurityContextHolder用于存储安全上下文(security context)的信息。当前操作的用户是谁,该用户是否已经被认证,他拥有哪些角色权限…这些都被保

Spring Security基于数据库验证流程详解

Spring Security 校验流程图 相关解释说明(认真看哦) AbstractAuthenticationProcessingFilter 抽象类 /*** 调用 #requiresAuthentication(HttpServletRequest, HttpServletResponse) 决定是否需要进行验证操作。* 如果需要验证,则会调用 #attemptAuthentica

Spring Security 从入门到进阶系列教程

Spring Security 入门系列 《保护 Web 应用的安全》 《Spring-Security-入门(一):登录与退出》 《Spring-Security-入门(二):基于数据库验证》 《Spring-Security-入门(三):密码加密》 《Spring-Security-入门(四):自定义-Filter》 《Spring-Security-入门(五):在 Sprin

Java架构师知识体认识

源码分析 常用设计模式 Proxy代理模式Factory工厂模式Singleton单例模式Delegate委派模式Strategy策略模式Prototype原型模式Template模板模式 Spring5 beans 接口实例化代理Bean操作 Context Ioc容器设计原理及高级特性Aop设计原理Factorybean与Beanfactory Transaction 声明式事物

Java进阶13讲__第12讲_1/2

多线程、线程池 1.  线程概念 1.1  什么是线程 1.2  线程的好处 2.   创建线程的三种方式 注意事项 2.1  继承Thread类 2.1.1 认识  2.1.2  编码实现  package cn.hdc.oop10.Thread;import org.slf4j.Logger;import org.slf4j.LoggerFactory

高效+灵活,万博智云全球发布AWS无代理跨云容灾方案!

摘要 近日,万博智云推出了基于AWS的无代理跨云容灾解决方案,并与拉丁美洲,中东,亚洲的合作伙伴面向全球开展了联合发布。这一方案以AWS应用环境为基础,将HyperBDR平台的高效、灵活和成本效益优势与无代理功能相结合,为全球企业带来实现了更便捷、经济的数据保护。 一、全球联合发布 9月2日,万博智云CEO Michael Wong在线上平台发布AWS无代理跨云容灾解决方案的阐述视频,介绍了

JAVA智听未来一站式有声阅读平台听书系统小程序源码

智听未来,一站式有声阅读平台听书系统 🌟 开篇:遇见未来,从“智听”开始 在这个快节奏的时代,你是否渴望在忙碌的间隙,找到一片属于自己的宁静角落?是否梦想着能随时随地,沉浸在知识的海洋,或是故事的奇幻世界里?今天,就让我带你一起探索“智听未来”——这一站式有声阅读平台听书系统,它正悄悄改变着我们的阅读方式,让未来触手可及! 📚 第一站:海量资源,应有尽有 走进“智听