当前位置:网站首页>@What happens if bean and @component are used on the same class?
@What happens if bean and @component are used on the same class?
2022-07-07 12:06:00 【Program ape DD_】
| Doubt description
lately , In the process of development , Found a way to write before , It's like this :

In my understanding ,@Configuration Add @Bean Will create a userName Not for null Of UserManager object , and @Component It will also create a userName by null Of UserManager object .
So we inject... Into other objects UserManager Object time , Which object is injected ?
Because the project has been online for a long time , Therefore, this writing method does not compile and report errors , There was no problem with the operation . I'll find my colleagues later to find out , Actually, I want :

take effect , In fact, it did take effect . So here comes the question :Spring How many... Are there in the container UserManager Object of type ?
| Spring Boot edition
Used in the project Spring Boot The version is :2.0.3.RELEASE. Object's scope Is the default value , That is to say singleton.
The results verify that
There are many ways to verify , Sure debug Follow the source code , have a look Spring How many... Are there in the container UserManager object , You can also go straight from UserManager Construction method , See which constructor methods are called , wait .
Let's start with the construction method , have a look UserManager How many instances did you instantiate .

Only parameterized constructors are called , The nonparametric construction method remains intact ( Not called at all ). If you want to know more , You can read :Spring The cycle of dependence , Detailed analysis of source code → Do you really need level 3 cache ?
https://www.cnblogs.com/youzhibing/p/14337244.html
since UserManager The constructor is called only once , So the previous question : Which object is injected . The answer is clear , There's no choice , Can only be @Configuration Add @Bean Created userName Not for null Of UserManager object .
Here comes the question : Why not @Component Created userName by null Of UserManager object ?
The source code parsing
@Configuration And @Component It's very close .

therefore @Configuration It can be component scan.
among ConfigurationClassPostProcessor And @Configuration Is closely linked , The class inheritance structure is as follows :

It has achieved BeanFactoryPostProcessor Interface and PriorityOrdered Interface .
About BeanFactoryPostProcessor, You can see :
https://www.cnblogs.com/youzhibing/p/10559337.html
from AbstractApplicationContext Of refresh Method called invokeBeanFactoryPostProcessors(beanFactory) Start , Follow the source code .

Now it's done com.lee.qsl Under bag component scan ,com.lee.qsl Package and sub package UserConfig、UserController and UserManager All scanned . Be careful , At the moment @Bean The processing of has not yet started ,UserManager It's through @Component And the scanned ; here Spring In the container beanDefinitionMap Medium UserManager That's true .

The next step is important , It is closely related to the answer we want .


Loop recursive processing UserConfig 、UserController and UserManager, Package them all into ConfigurationClass , Recursive scanning BeanDefinition. After the cycle , Let's see configClasses.

UserConfig bean In the definition beanMethods There's an element in [BeanMethod:name=userManager,declaringClass=com.lee.qsl.config.UserConfig].
Then we went down , Let's take a closer look at the link where the answer appears .

Did you find anything ?@Component Embellished UserManager The definition is directly overridden as @Configuration [email protected] Embellished UserManager Definition .Bean The type is also defined by ScannedGenericBeanDefinition replaced ConfigurationClassBeanDefinition.
Subsequently passed BeanDefinition When creating an instance , The nature created is @[email protected] Embellished UserManager, That is, it will reflect the call UserManager The parametric construction method of .
Since then , The answer is clear .Spring In fact, it gives a hint :
2021-10-03 20:37:33.697 INFO 13600 --- [ main] o.s.b.f.s.DefaultListableBeanFactory : Overriding bean definition for bean 'userManager' with a different definition: replacing [Generic bean: class [com.lee.qsl.manager.UserManager]; scope=singleton; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null; defined in file [D:\qsl-project\spring-boot-bean-component\target\classes\com\lee\qsl\manager\UserManager.class]] with [Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=userConfig; factoryMethodName=userManager; initMethodName=null; destroyMethodName=(inferred); defined in class path resource [com/lee/qsl/config/UserConfig.class]]Only the log level is info , It's too inconspicuous .
Spring Upgrade optimization
Probably Spring The team realized info The level is too inconspicuous , Or realize that the direct coverage is not reasonable . So in Spring 5.1.2.RELEASE (Spring Boot It is 2.1.0.RELEASE ) Optimization is made .
Let's see in detail .

Start direct error reporting ,Spring Tips are also given .
The bean 'userManager', defined in class path resource [com/lee/qsl/config/UserConfig.class], could not be registered. A bean with that name has already been defined in file [D:\qsl-project\spring-boot-bean-component\target\classes\com\lee\qsl\manager\UserManager.class] and overriding is disabled.Let's follow the source code , Mainly look at and Spring 5.0.7.RELEASE The difference between .

New configuration item allowBeanDefinitionOverriding To control whether BeanDefinition Cover , Not allowed by default . We can configure... In the configuration file :spring.main.allow-bean-definition-overriding=true , allow BeanDefinition Cover . This treatment is better , Leave the choice to the developer , Instead of dealing with it secretly , It has achieved the effect that developers want .
total junction
Spring 5.0.7.RELEASE ( Spring Boot 2.0.3.RELEASE ) Support @Configuration+ @Bean And @Component Act on the same class at the same time . When starting, it will give info Level log prompt , At the same time @[email protected] Embellished BeanDefinition overwrite @Component Embellished BeanDefinition.
Maybe Spring The team realized that the above treatment was not appropriate , So in Spring 5.1.2.RELEASE Optimization is made . Added configuration item :allowBeanDefinitionOverriding, Give the initiative to the developer , It's up to the developer to decide whether to allow coverage .
| Add
About allowBeanDefinitionOverriding, Wrong front , I went to the source code , Supplemented as follows .Spring 1.2 introduction DefaultListableBeanFactory When it's time private boolean allowBeanDefinitionOverriding=true;, The default is to allow BeanDefinition Cover .

Spring4.1.2 introduction isAllowBeanDefinitionOverriding() Method .

Spring From beginning to end, the default is to allow BeanDefinition Covered , The change is Spring Boot ,Spring Boot 2.1.0 Not covered before Spring Of allowBeanDefinitionOverriding The default value is , Still allowed BeanDefinition Covered .
Spring Boot 2.1.0 in SpringApplication Defines private properties :allowBeanDefinitionOverriding.
The specified value is not displayed , So the default is false , After the Spring Boot During startup , Will overwrite with this value Spring Medium allowBeanDefinitionOverriding The default value of .

About allowBeanDefinitionOverriding, I think you should have made it clear .
We have created a high-quality technical exchange group , With good people , I will be excellent myself , hurriedly Click Add group , Enjoy growing up together . in addition , If you want to change jobs recently , Years ago, I spent 2 A wave of large factory classics were collected in a week , Those who are ready to change jobs after the festival can Click here to get !
Recommended reading
··································
Hello , I'm a procedural ape DD,10 Old driver developed in 、 Alibaba cloud MVP、 Tencent cloud TVP、 I have published books and started a business 、 State-owned enterprises 4 In the Internet 6 year . From ordinary developers to architects 、 Then to the partner . Come all the way , My deepest feeling is that I must keep learning and pay attention to the frontier . As long as you can hold on , Think more 、 Don't complain 、 Do it frequently , It's easy to overtake on a curve ! therefore , Don't ask me what I'm doing now, whether it's in time . If you are optimistic about one thing , It must be persistence to see hope , Instead of sticking to it when you see hope . believe me , Just stick to it , You must be better than now ! If you don't have any direction , You can pay attention to me first , Some cutting-edge information is often shared here , Help you accumulate the capital to overtake on the curve .
边栏推荐
- 全球首堆“玲龙一号”反应堆厂房钢制安全壳上部筒体吊装成功
- 【全栈计划 —— 编程语言之C#】基础入门知识一文懂
- Swiftui swift internal skill: five skills of using opaque type in swift
- 【滤波跟踪】基于matlab捷联惯导仿真【含Matlab源码 1935期】
- Flet教程之 18 Divider 分隔符组件 基础入门(教程含源码)
- Le Cluster kubernets en cours d'exécution veut ajuster l'adresse du segment réseau du pod
- Visual Studio 2019 (LocalDB)\MSSQLLocalDB SQL Server 2014 数据库版本为852无法打开,此服务器支持782版及更低版本
- NPC Jincang was invited to participate in the "aerospace 706" I have an appointment with aerospace computer "national Partner Conference
- Flet教程之 15 GridView 基础入门(教程含源码)
- Let digital manage inventory
猜你喜欢

【神经网络】卷积神经网络CNN【含Matlab源码 1932期】

Rationaldmis2022 array workpiece measurement

In SQL, I want to set foreign keys. Why is this problem
![108. Network security penetration test - [privilege escalation 6] - [windows kernel overflow privilege escalation]](/img/c0/8a7b52c46eadd27cf4784ab2f32002.png)
108. Network security penetration test - [privilege escalation 6] - [windows kernel overflow privilege escalation]

How to connect 5V serial port to 3.3V MCU serial port?

Explore cloud database of cloud services together

Reasons for the failure of web side automation test

Completion report of communication software development and Application
![112.网络安全渗透测试—[权限提升篇10]—[Windows 2003 LPK.DDL劫持提权&msf本地提权]](/img/b6/6dfe9be842204567096d1f4292e8e7.png)
112.网络安全渗透测试—[权限提升篇10]—[Windows 2003 LPK.DDL劫持提权&msf本地提权]

How much do you know about excel formula?
随机推荐
小红书微服务框架及治理等云原生业务架构演进案例
How to write test cases for test coupons?
正在運行的Kubernetes集群想要調整Pod的網段地址
Is it safe to open Huatai's account in kainiu in 2022?
Cmu15445 (fall 2019) project 2 - hash table details
EasyUI learn to organize notes
About how to install mysql8.0 on the cloud server (Tencent cloud here) and enable local remote connection
Unity 贴图自动匹配材质工具 贴图自动添加到材质球工具 材质球匹配贴图工具 Substance Painter制作的贴图自动匹配材质球工具
Present pod information to the container through environment variables
108.网络安全渗透测试—[权限提升篇6]—[Windows内核溢出提权]
本地navicat连接liunx下的oracle报权限不足
【最短路】ACwing 1127. 香甜的黄油(堆优化的dijsktra或spfa)
Steps of redis installation and self startup configuration under CentOS system
NPC Jincang was invited to participate in the "aerospace 706" I have an appointment with aerospace computer "national Partner Conference
【神经网络】卷积神经网络CNN【含Matlab源码 1932期】
Fleet tutorial 19 introduction to verticaldivider separator component Foundation (tutorial includes source code)
问下flinkcdc2.2.0的版本,支持并发,这个并发是指多并行度吗,现在发现,mysqlcdc全
Various uses of vim are very practical. I learned and summarized them in my work
千人规模互联网公司研发效能成功之路
【纹理特征提取】基于matlab局部二值模式LBP图像纹理特征提取【含Matlab源码 1931期】