Spring's overriding bean

后端 未结 8 1463
忘了有多久
忘了有多久 2020-12-01 03:02

Can we have duplicate names for the same bean id that is mentioned in the XML? If not, then how do we override the bean in Spring?

8条回答
  •  离开以前
    2020-12-01 03:28

    Question was more about XML but as annotation are more popular nowadays and it works similarly I'll show by example. Let's create class Foo:

    public class Foo {
        private String name;
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    }
    

    and two Configuration files (you can't create one):

    @Configuration
    public class Configuration1 {
        @Bean
        public Foo foo() {
            Foo foo = new Foo();
            foo.setName("configuration1");
            return foo;
        }
    }
    

    and

    @Configuration
    public class Configuration2 {
        @Bean
        public Foo foo() {
            Foo foo = new Foo();
            foo.setName("configuration2");
            return foo;
        }
    }
    

    and let's see what happens when calling foo.getName():

    @SpringBootApplication
    public class OverridingBeanDefinitionsApplication {
    
        public static void main(String[] args) {
            SpringApplication.run(OverridingBeanDefinitionsApplication.class, args);
    
            AnnotationConfigApplicationContext applicationContext =
                    new AnnotationConfigApplicationContext(
                            Configuration1.class, Configuration2.class);
    
            Foo foo = applicationContext.getBean(Foo.class);
            System.out.println(foo.getName());
        }
    }
    

    in this example result is: configuration2. The Spring Container gets all configuration metadata sources and merges bean definitions in those sources. In this example there are two @Beans. Order in which they are fed into ApplicationContext decide. You can flip new AnnotationConfigApplicationContext(Configuration2.class, Configuration1.class); and result will be configuration1.

提交回复
热议问题