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]
In this case you should have something like this:
And then in
Main
class you should invoke next ones:A good article about how it work you can find here: spring-same-class-multiple-beans