In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-31 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly introduces "how to solve the problems that may be caused by configuring Bean with the same id or name in Spring". In daily operation, it is believed that many people have doubts about how to configure id or Bean with the same name in Spring. The editor consulted all kinds of materials and sorted out simple and useful operation methods. I hope it will be helpful to answer the question of "how to solve the problems that may be caused by configuring id or the same Bean in name in Spring"! Next, please follow the editor to study!
I. background
If you configure the same ID or name in xml, it may cause some problems, which we will explore and solve today.
Second, the question
1. The id of the same bean is configured in the same xml. EX:
In this case, the exception "Cannot register bean definition [xxx] for bean xxx: There is already [xxx] bound."
2. Configure the id of the same bean in different xml. EX:
Test1.xml
Test2.xml
In this case, the bean in the text2.xml will directly overwrite the bean,Spring in the text1.xml and eventually only load the bean in the text2.xml into the IOC container.
At this point, spring will not report an error, but will only print info-level log information. In this case, "Overriding bean definition for bean xxx with a different definition: replacing [xxx] with [xxx]", it is difficult to troubleshoot the problem.
Third, solve the problem
By looking at the spring source code, we find that there is a key variable allowBeanDefinitionOverriding when the springIOC container is initialized.
Let's take a look at the source code:
@ Override public void registerBeanDefinition (String beanName, BeanDefinition beanDefinition) throws BeanDefinitionStoreException {/ / verify that beanName and beanDefinition are not empty Assert.hasText (beanName, "Bean name must not be empty"); Assert.notNull (beanDefinition, "BeanDefinition must not be null") / / verify the parsed BeanDefiniton if (beanDefinition instanceof AbstractBeanDefinition) {try {((AbstractBeanDefinition) beanDefinition) .validate () } catch (BeanDefinitionValidationException ex) {throw new BeanDefinitionStoreException (beanDefinition.getResourceDescription (), beanName, "Validation of bean definition failed", ex);}} BeanDefinition oldBeanDefinition / / get the BeanDefinition oldBeanDefinition = this.beanDefinitionMap.get (beanName) of the specified beanName from the cache / / if if (oldBeanDefinition! = null) {/ / if it exists but overwrite is not allowed Throw an exception if (! isAllowBeanDefinitionOverriding ()) {- 6 throw new BeanDefinitionStoreException (beanDefinition.getResourceDescription (), beanName) "Cannot register bean definition [" + beanDefinition + "] for bean'" + beanName + "': There is already [" + oldBeanDefinition + "] bound.") } / / overwrite the ROLE whose beanDefinition is larger than that of the covered beanDefinition Print info log else if (oldBeanDefinition.getRole () < beanDefinition.getRole ()) {/ / e.g. Was ROLE_APPLICATION Now overriding with ROLE_SUPPORT or ROLE_INFRASTRUCTURE if (this.logger.isWarnEnabled ()) {this.logger.warn ("Overriding user-defined bean definition for bean'" + beanName + "'with a framework-generated bean definition: replacing [" + OldBeanDefinition + "] with [" + beanDefinition + "]") }} else if (! beanDefinition.equals (oldBeanDefinition)) {if (this.logger.isInfoEnabled ()) {this.logger.info ("Overriding bean definition for bean" + beanName +) "'with a different definition: replacing [" + oldBeanDefinition + "] with [" + beanDefinition + "]") }} else {if (this.logger.isDebugEnabled ()) {this.logger.debug ("Overriding bean definition for bean'" + beanName +) "'with an equivalent definition: replacing [" + oldBeanDefinition + "] with [" + beanDefinition + "]") }} / / allow overwriting, directly overwriting the original BeanDefinition to the beanDefinitionMap. This.beanDefinitionMap.put (beanName, beanDefinition);}
You can see in line 6 that you decide whether to override or throw an exception by judging the value of the allowBeanDefinitionOverriding variable, while the value of allowBeanDefinitionOverriding defaults to true. So it is overridden directly by default and no exception is thrown.
So it's easy to think that changing the value of allowBeanDefinitionOverriding to false will solve the problem.
Looking at the source code, we find that the DefaultListableBeanFactory class provides a method for assigning allowBeanDefinitionOverriding variables:
Public void setAllowBeanDefinitionOverriding (boolean allowBeanDefinitionOverriding) {this.allowBeanDefinitionOverriding = allowBeanDefinitionOverriding;}
So all we have to do is call this method and assign allowBeanDefinitionOverriding to false.
So how to modify it? Let's take a look at which classes call the setAllowBeanDefinitionOverriding () method:
As you can see, this method is called in the AbstractRefreshableApplicationContext class, and we continue to follow up on this class to see:
Protected void customizeBeanFactory (DefaultListableBeanFactory beanFactory) {if (this.allowBeanDefinitionOverriding! = null) {beanFactory.setAllowBeanDefinitionOverriding (this.allowBeanDefinitionOverriding);} if (this.allowCircularReferences! = null) {beanFactory.setAllowCircularReferences (this.allowCircularReferences);}}
We found that it was called in the customizeBeanFactory () method, and then we traced the this.allowBeanDefinitionOverriding variable to see where it was set:
/ * * Set whether it should be allowed to override bean definitions by registering * a different definition with the same name, automatically replacing the former. * If not, an exception will be thrown. Default is "true". * @ see org.springframework.beans.factory.support.DefaultListableBeanFactory#setAllowBeanDefinitionOverriding * / public void setAllowBeanDefinitionOverriding (boolean allowBeanDefinitionOverriding) {this.allowBeanDefinitionOverriding = allowBeanDefinitionOverriding;}
You can see that AbstractRefreshableApplicationContext exposes the setAllowBeanDefinitionOverriding () method to set the value of the allowBeanDefinitionOverriding variable. Look directly in the AbstractRefreshableApplicationContext class to see where the method was called and find that it can't be found, so let's see what subclasses it has.
We'll find a very familiar class: ClassPathXmlApplicationContext is easy next, and we can set the value of the allowBeanDefinitionOverriding variable by calling the setAllowBeanDefinitionOverriding () method of the parent class through the ClassPathXmlApplicationContext class.
The code is as follows:
Public static void main (String [] args) {ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext (new String [] {"context.xml", "context1.xml"}, false); / / pay attention to the order of context. It can be predicted that there must be a conflict in context1.xml. / / Note that this false data is set to false, which means that you will not take the initiative to refresh the bean factory and parse xml applicationContext.setAllowBeanDefinitionOverriding (false). / / assign the parameter allowBeanDefinitionOverriding applicationContext.refresh () of application; / / now you need to manually start the refresh operation Student student = (Student) applicationContext.getBean ("student"); System.out.println (student.toString ());}
The work is done.
At this point, the study on "how to solve the problems that may be caused by configuring id or name with the same Bean in Spring" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.