这是行不通的,因为这个属性注入是基于对象上的 getter 和 setter 应该持有 @ConfigurationProperties
像这样定义一个包含您想要的属性的类:
@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;
}
}