Spring,根据 Bean 的字段值之一在 Bean 实例中注入属性,这可能吗?

Spring, inject properties in a Bean instance based one of that Bean's field value, is it possible?

我有一个用于配置 Web 服务客户端的 Pojo:

public class ServiceConfig {

    private String url;
    private String endpoint;
    private String serviceName;

    public ServiceConfig(String serviceName) {
        super();
        this.serviceName = serviceName;
    }

}

现在,这就是我的 application.properties 文件的样子:

service1.url=http://localhost:8087/
service1.endpoint=SOME_ENDPOIT1
service2.url=http://localhost:8085/
service2.endpoint=SOME_ENDPOIT2
service3.url=http://localhost:8086/
service3.endpoint=SOME_ENDPOIT3
service4.url=http://localhost:8088/
service4.endpoint=SOME_ENDPOIT4

我想要实现的是 Spring 在我像这样实例化 ServiceConfig 时注入正确的属性:

ServiceConfig sc = new ServiceConfig("service1");

可能吗?

您是只使用 spring 还是同时使用 spring-boot?

如何将 org.springframework.core.env.Environment 注入您的 pojo 并使用它进行配置。

所以这样的东西可以工作:

public class ServiceConfig {

    private String url;
    private String endpoint;
    private String serviceName;

    public ServiceConfig(String serviceName, Environment env) {
        // TODO assert on serviceName not empty 
        this.serviceName = serviceName;
        this.url = env.getProperty(serviceName.concat(".url");
        this.endpoint = env.getProperty(serviceName.concat(".endpoint"); 
    }
}

我想可能会有一个 simpler/more 优雅的解决方案,但我不知道你的情况。

spring-引导版本

使用 spring 启动只需定义您的 pojo(字段名称必须匹配 属性 名称)

public class ServiceConfig {

    private String url;
    private String endpoint;

    // getters setters
}

然后在某些配置中你可以这样做(注意:ConfigurationProperties 中的值是你在 application.properties 中配置的前缀):

@Configuration
public class ServicesConfiguration {

    @Bean
    @ConfigurationProperties("service1")
    ServiceConfig service1(){
        return new ServiceConfig();
    }

    @Bean
    @ConfigurationProperties("service2")
    ServiceConfig service2(){
        return new ServiceConfig();
    }
}