Search code examples
javaspringclassspring-annotationsspring-framework-beans

Accessing Bean with same name


When I have two beans with the same name, the first one I defined always runs when I try to use them. How can I make the second bean run instead? I even tried using the @Primary annotation, but it didn't work.

This is the Configuration class

package com.springdemo.learnspring;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

record Person(String name, int age) {}

@Configuration
public class HelloWorldConfiguration {
   
    @Bean (name = "GetPerson")
    public Person person1() {
        return new Person("Person", 24);
    }

    @Bean (name = "GetPerson")
    // @Primary  // Didn't work
    public Person person2() {
        return new Person("Person2", 21);
    }

}

This is the Main ApplicationContext class

package com.springdemo.learnspring;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class LearnSpringApplication {
    public static void main(String[] args) {
        var context = new AnnotationConfigApplicationContext(HelloWorldConfiguration.class);
        
        System.out.println(context.getBean("GetPerson"));
    }
}

I'm always getting the below output. Even though I annotated the person2() method with primary, How can I call the person2() bean?

Person[name=Person, age=24]


Solution

  • In this case you should have something like this:

    record Person(String name, int age) {}
    
        @Configuration
        public class HelloWorldConfiguration {
          @Bean
          public Person person1() {
            return new Person("Person", 24);
          }
          @Bean
          public Person person2() {
            return new Person("Person2", 21);
          }
        }
    

    Here, @Bean instantiates two beans with ids the same as the method names, and registers them within the BeanFactory (Spring container) interface. Next, we can initialize the Spring container, and request any of the beans from the Spring container.

    And then in Main class you should invoke next ones:

    public class LearnSpringApplication {
        public static void main(String[] args) {
            var context = new AnnotationConfigApplicationContext(HelloWorldConfiguration.class);
            
         
          System.out.println(context.getBean("person1"));
          System.out.println(context.getBean("person2"));
        }
    }
    

    A good article about how it work you can find here: spring-same-class-multiple-beans