Announcement Announcement Module
No announcement yet.
Same Bean name in two xml files - doesnt give error ? Page Title Module
Move Remove Collapse
Conversation Detail Module
  • Filter
  • Time
  • Show
Clear All
new posts

  • Same Bean name in two xml files - doesnt give error ?

    I tried the following. Inside META-INF/spring I created two config files. config1.xml and config2.xml.

    I have this inside config1.xml

    <beans:bean id="test" class="com.test.Test"></beans:bean>

    When i copy the same bean into config2.xml I expect a error. But it doesnt throw a error. Why so ?

    If i copy in teh same config file it throws error , but not in different files it doesnt.Isnt it one applicationContext which is created , then why is teh behavior different ?

  • #2
    Id is a special keyword (it is an xml keyword) hence it has to be unique in a file (this isn't a spring limit it is a limit due to the xml keyword).

    You can have beans with the same name, however the last bean loaded is the one that remains in the ApplicationContext, it basically overrides the previous one.

    Which can be quite handy for testing, for creating defaults which customers can override etc.


    • #3
      i tried copying this in a single file

      <beans:bean name="test" class="com.test.Test"></beans:bean>
      <beans:bean name="test" class="com.test.Test"></beans:bean>

      and i get teh following error

       org.springframework.beans.factory.parsing.BeanDefinitionParsingException: Configuration problem: Bean name 'test' is already used in this file
      Offending resource: URL [bundleentry://77.fwk18661065/META-INF/spring/config.xml]


      • #4
        My explanation wasn't complete you can have beans with the same name in the same ApplicationContext but they have to be in different files.

        It is (validly imho) considered a bug/issue to have beans with the same name in the same file because why would you want to do that. Overriding by loading a different file is a different usecase for the reasons (and probably more you can come up with) mentioned earlier.


        • #5
          I got it :-) Thanks for the clarification


          • #6
            Simply if you check the xsd , it shows that bean id is nothing but IDREF and hence single in a singe file.