Difference between using bean id and name in Spring configuration file

后端 未结 6 1058
忘了有多久
忘了有多久 2020-12-04 05:24

Is there any difference between using an id attribute and name attribute on a element in a Spring configuration file?

6条回答
  •  有刺的猬
    2020-12-04 06:06

    let me answer below question

    Is there any difference between using an id attribute and using a name attribute on a tag,

    There is no difference. you will experience same effect when id or name is used on a tag .

    How?

    Both id and name attributes are giving us a means to provide identifier value to a bean (For this moment, think id means id but not identifier). In both the cases, you will see same result if you call applicationContext.getBean("bean-identifier"); .

    Take @Bean, the java equivalent of tag, you wont find an id attribute. you can give your identifier value to @Bean only through name attribute.

    Let me explain it through an example :
    Take this configuration file, let's call it as spring1.xml

    
    
      
      
    
    

    Spring returns Foo object for, Foo f = (Foo) context.getBean("foo"); . Replace id="foo" with name="foo" in the above spring1.xml, You will still see the same result.

    Define your xml configuration like,

    
    
      
      
    
    

    You will get BeanDefinitionParsingException. It will say, Bean name 'fooIdentifier' is already used in this element. By the way, This is the same exception you will see if you have below config




    If you keep both id and name to the bean tag, the bean is said to have 2 identifiers. you can get the same bean with any identifier. take config as


    the following code prints true

    FileSystemXmlApplicationContext context = new FileSystemXmlApplicationContext(...);
    Foo fooById = (Foo) context.getBean("fooById")// returns Foo object;
    Foo fooByName = (Foo) context.getBean("fooByName")// returns Foo object;
    System.out.println(fooById == fooByName) //true
    

提交回复
热议问题