访问同名Bean

问题描述 投票:0回答:1

当我有两个同名的 bean 时,当我尝试使用它们时,我定义的第一个始终会运行。我怎样才能让第二个bean运行呢?我什至尝试使用@Primary注释,但它不起作用。

这是配置类

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);
    }

}

这是主ApplicationContext类

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"));
    }
}

我总是得到以下输出。即使我用primary注释了person2()方法,我如何调用person2() bean?

人[姓名=人,年龄=24]

java spring class spring-annotations spring-framework-beans
1个回答
0
投票

在这种情况下,你应该有这样的东西:

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);
      }
    }

这里@Bean实例化了两个bean,id与方法相同 名称,并将它们注册到 BeanFactory(Spring 容器)中 界面。接下来,我们可以初始化Spring容器,并请求 Spring 容器中的任何 Bean。

然后在

Main
类中,您应该调用下一个:

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"));
    }
}

您可以在这里找到一篇关于它如何工作的好文章:spring-same-class-multiple-beans

© www.soinside.com 2019 - 2024. All rights reserved.