gpt4 book ai didi

java - Spring 启动 : read from yaml using @ConfigurationProperties not working with @Data

转载 作者:行者123 更新时间:2023-12-02 16:05:54 25 4
gpt4 key购买 nike

我正在尝试从 application.yml 中检索值。下面的最后一行显示 kafkaConfig 为空,无法读取。如何正确设置 Kafka 配置和代码以从 json 文件中读取?我们正在使用 @Data 而不是 getters/setters。

KafkaConfig.java

@Configuration
@ConfigurationProperties("kafka")
@Data
public class KafkaConfig {
private String topic;
private String event;
}

Application.yml

kafka:
topic: "testTopic"
event: "testEvent"

KafkaProducerBeans.java

@Component
public class KafkaProducerBeans {

@Autowired
private KafkaConfig kafkaConfig;

public KafkaProducerBeans(KafkaConfig kafkaConfig) {
this.kafkaConfig = kafkaConfig;
}

@Bean(name = "kafkaTestClient")
public String getData() {
return kafkaConfig.getTopic(); // final line is creating null for kafka Config
}

资源:https://codingnconcepts.com/spring-boot/spring-configuration-properties-using-yml/

最佳答案

我认为将属性绑定(bind)到 pojos 的推荐方法是使用 @EnableConfigurationProperties 注释,如下所示:

KafkaConfig.java

@ConfigurationProperties("kafka")
@Data
public class KafkaConfig {
private String topic;
private String event;
}

KafkaProducerBeans.java

@Component
@EnableConfigurationProperties(KafkaConfig.class)
public class KafkaProducerBeans {

private final KafkaConfig kafkaConfig;

@Autowired
public KafkaProducerBeans(KafkaConfig kafkaConfig) {
this.kafkaConfig = kafkaConfig;
}

// [...]
}

更多细节请引用Spring官方文档:

关于java - Spring 启动 : read from yaml using @ConfigurationProperties not working with @Data,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69396498/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com