【问题标题】:Spring @Configuration classes, how to configure multiple instances of the same bean passing different parametersSpring @Configuration 类,如何配置同一个bean的多个实例传递不同的参数
【发布时间】:2017-01-04 18:44:58
【问题描述】:

我有一个 Spring Java Configuration 类,它在里面定义了一个 bean,例如:

@Configuration
public class SomeConfig{

    private String someProperty;  

    public SomeConfig(String someProperty){
        this.someProperty=someProperty;
    }

    @Bean
    public SomeBean someBean(){
        SomeBean s = new SomeBean(someProperty);
        return s;    
    }
}

我需要有多个SomeBean 实例,每个实例都配置有不同的someProperty 值。

  1. 在 Spring Boot 应用程序中是否可以多次 @Import 同一个类? 自行回答:如果您导入相同的@Configuration 类,它将覆盖现有的。
  2. 如何使用 Spring Java Config 完成这样的事情?

更新:

在 XML 中我可以做到:

<bean class="x.y.z.SomeBean">
    <constructor-arg value="1"/>
</bean>
<bean class="x.y.z.SomeBean">
    <constructor-arg value="2"/>
</bean>

我正在寻找具有 Java Config 的等效项

【问题讨论】:

  • FactoryBean
  • 我可以定义@Bean FactoryBean&lt;SomeBean&gt;,但我仍然不知道如何指定不同的 someProperty 值。
  • 如果你将一些bean对象注入到其他bean中,你可以这样定义; @Bean public SomeBean someBean(String someProperty) 所以,你将定义 someBean 一次,你可以使用相同的定义创建多个对象
  • 原型范围是一个选项吗?
  • 不,应该正好有 n 个实例。

标签: spring spring-mvc spring-boot spring-java-config


【解决方案1】:

我只需要使用另一个 @Configuration 类,它根据需要定义了尽可能多的 SomeConfig bean:

@Configuration
public class ApplicationConfig{

    @Bean
    public SomeConfig someConfig1(){
        return new SomeConfig("1");
    }

    @Bean
    public SomeConfig someConfig2(){
        return new SomeConfig("2"); 
    }
}

【讨论】:

    【解决方案2】:
    @Configuration
    public class SomeConfig{
    
        private String someProperty;  
    
        @Bean
        public OtherBean otherBeanOne(){
            OtherBean otherBean = new OhterBean();
            otherBean.setSomeBean(someBean("property1"));
            return otherBean;    
        }
    
    
        @Bean
        public OtherBean otherBeanTwo(){
            OtherBean otherBean = new OhterBean();
            otherBean.setSomeBean(someBean("property2"));
            return otherBean;    
        }
    
        @Bean
        public SomeBean someBean(String someProperty){
            SomeBean s = new SomeBean(someProperty);
            return s;    
        }
    
    
    }
    

    【讨论】:

    • 可能不是问题中列出的所有项目的答案,但我希望它有所帮助。
    • 感谢您的建议,但重点是我需要在 config 中定义 someProperty 值并拥有 n 个 SomeBean 实例,而不需要包装类(OtherBean)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-01
    • 1970-01-01
    • 2012-05-09
    • 1970-01-01
    相关资源
    最近更新 更多