Spring MVC 如何将带前缀的属性注入到java.util.properties中?

9njqaruj  于 2022-11-14  发布在  Spring
关注(0)|答案(3)|浏览(275)

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

}
qgzx9mmu

qgzx9mmu1#

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

hgb9j2n62#

您可以定义使用@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

l3zydbqr

l3zydbqr3#

@自动布线环境;{返回新属性(){ @覆盖公共字符串getProperty(字符串名称){返回环境.getProperty(名称);} }; }

相关问题