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



Spring boot 提供了一种优雅的方法,可以使用 @ConfigurationProperties(prefix = "foo") 将带有特定键前缀的属性注入到 Configuration 类中。这显示在这里和这里。问题是,如何将前缀属性注入实例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;
    }
}

这是行不通的,因为此属性注入基于应保存@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;
  }
}

您可以定义一个用 @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(

@Autowired 环境环境;private Properties getProperties(( { return new Properties(( { @Override public String getProperty(String name( { return environment.getProperty(name(; } }; }

相关内容

最新更新