如何将前缀属性注入java.util.Properties?

时间:2018-01-24 07:42:26

标签: java spring spring-mvc spring-boot

Spring引导提供了一种优雅的方法,使用@ConfigurationProperties(prefix = "foo")将带有特定键的属性注入到Configuration类中。这显示为herehere。问题是,如何将前缀属性注入java.util.Properties实例,如下所示?

@Configuration
@EnableConfigurationProperties
public class FactoryBeanAppConfig {

    @Bean
    @ConfigurationProperties(prefix = "kafka")
    public Producer<String, String> producer(Properties properties) throws Exception {
        Producer<String, String> producer = new KafkaProducer<String, String>(properties);
        return producer;
    }

}

2 个答案:

答案 0 :(得分:2)

这不起作用,因为此属性注入基于应该保存@ConfigurationProperties的对象上的getter和setter 定义一个包含所需属性的类:

@ConfigurationProperties(prefix = "kafka.producer")
public class MyKafkaProducerProperties {

  private int foo;

  private string bar;

  // Getters and Setter for foo and bar

}

然后在您的配置中使用它

@Configuration
@EnableConfigurationProperties(MyKafkaProducerProperties.class)
public class FactoryBeanAppConfig {

  @Bean
  public Producer<String, String> producer(MyKafkaProducerProperties kafkaProperties) throws Exception {
    Properties properties = new Properties();
    properties.setProperty("Foo", kafkaProperties.getFoo());
    properties.setProperty("Bar", kafkaProperties.getBar());
    Producer<String, String> producer = new KafkaProducer<String, String>(properties);
    return producer;
  }
}

<强>更新

由于您评论说您不希望将每个属性表示为java代码,因此您可以使用HashMap作为@ConfigurationProperties

中的唯一属性
@ConfigurationProperties(prefix = "kafka")
public class MyKafkaProducerProperties {

  private Map<String, String> producer= new HashMap<String, String>();

  public Map<String, String> getProducer() {
    return this.producer;
  }
}

application.properties中,您可以指定如下属性:

kafka.producer.foo=hello
kafka.producer.bar=world

在您的配置中,您可以像这样使用它:

@Configuration
@EnableConfigurationProperties(MyKafkaProducerProperties.class)
public class FactoryBeanAppConfig {

  @Bean
  public Producer<String, String> producer(MyKafkaProducerProperties kafkaProperties) throws Exception {

    Properties properties = new Properties();

    for ( String key : kafkaProperties.getProducer().keySet() ) {
     properties.setProperty(key, kafkaProperties.getProducer().get(key));
    }

    Producer<String, String> producer = new KafkaProducer<String, String>(properties);
    return producer;
  }
}

答案 1 :(得分:0)

您可以定义一个用@ConfigurationProperties注释的新bean,如下所示:

@Bean
@ConfigurationProperties(prefix = "kafka")
public Properties kafkaProperties() {
    return new Properties();
}

@Bean
public Producer<String, String> producer() throws Exception {
    return new KafkaProducer<String, String>(kafkaProperties());
}

(摘自https://stackoverflow.com/a/50810923/500478