【问题标题】:Spring bean with placeholder create a second bean with different profile带有占位符的 Spring bean 创建具有不同配置文件的第二个 bean
【发布时间】:2020-03-04 23:55:33
【问题描述】:

假设有一个像这样的 Spring 托管 bean:

@Component
@Profile("prod")
public class MyBean {

    @Value("${x.y.id:-1}")
    private int id;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }
}

另外,x.y.id 属性确实存在于application-prod.properties 文件中。

现在,如果我想在这样的配置类中使用相同的类创建另一个具有不同配置文件的托管 bean:

@Profile("dev")
@Bean
public MyBean myBean() {
    MyBean myBean = new MyBean();
    myBean.setId(10);
    return myBean;
}

它不起作用,因为 id 字段最终会以 -1 值结束,因为占位符的默认值具有最终确定性。

问题在这种情况下是否可以拥有第二个托管 bean?


在 application-dev.properties 中添加 x.y.id=10 确实适用于上述情况,但不适用于此情况:

@Profile("dev")
@Bean
public MyBean myBean() {
    MyBean myBean = new MyBean();
    myBean.setId(10);
    return myBean;
}

@Profile("dev")
@Bean
public MyBean myAnotherBean() {
    MyBean myBean = new MyBean();
    myBean.setId(20);
    return myBean;
}

【问题讨论】:

  • 如果您需要设置不同的值,只需在 application-dev.properties 文件中添加 x.y.id=10

标签: java spring spring-boot


【解决方案1】:

为了保持同质,您可以简单地回退到拥有一个application-dev.properties 文件并在那里设置属性。

【讨论】:

    【解决方案2】:

    我不确定什么是“占位符的默认值有定论...”

    但我认为以下应该可行:

    您可以重写MyBean 类,这样它就不会使用@Value 并且通常会使用构造函数注入:

    public class MyBean {
    
        private final int id;
    
        public MyBean(int id) {this.id = id;}
    
        public int getId() {
            return id;
        }
    }
    

    在这种情况下,配置可以定义如下:

    @Configuration
    @Profile("prod") // also possible to be used per bean
    public class MyProductionConfiguration {
    
        @Bean
        public MyBean myBean( @Value("${x.y.id:-1}") int id) {
           return new MyBean(id);
        }
    }
    
    @Configuration
    @Profile("dev")
    public class MyDevConfiguration {
    
        @Bean
        public MyBean myBean() {
           return new MyBean(10);
        }
    }
    
    

    【讨论】:

    • "placeholder's default value has the final word..." 表示第二个 bean 具有 id=-1,即使我将值设置为 10。您的想法很好,但我无法更改 @987654326 @代码。
    猜你喜欢
    • 2017-08-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-02
    • 2019-09-28
    • 2011-03-21
    • 2023-04-01
    • 1970-01-01
    相关资源
    最近更新 更多