Spring,基于Bean的字段值之一在Bean实例中注入属性,是否可能?

时间:2018-01-09 13:11:56

标签: spring properties configuration javabeans

我有一个用于配置webservices客户端的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”);

有可能吗?

1 个答案:

答案 0 :(得分:0)

您是使用弹簧还是弹簧靴?

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

我想可能会有一个更简单/更优雅的解决方案,但我不了解你的情况。

spring-boot version

使用spring boot,只需定义你的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();
    }
}