当前位置: 首页 > 知识库问答 >
问题:

Spring Boot:使用@ConfigurationProperties从yaml读取,但不使用@Data

冷涵忍
2023-03-14

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

KafkaConfig.java

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

应用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/

共有3个答案

严狐若
2023-03-14

@组件扫描(basePackages=“PATH”)

PATH:您希望它查找的包路径

@ComponentScan(basePackages ="PATH" )
@Configuration
@Import(value = {
    KafkaProducerBeans.class
})
public class AppConfig{

}
时宾实
2023-03-14

在类KafkaConfig上添加一个注释@EnableConfigurationProperties

KafkaConfig.java

@Configuration
@EnableConfigurationProperties    // new added annotation
@ConfigurationProperties("kafka")
@Data
public class KafkaConfig {
    private String topic;
    private String event;
}
黄毅
2023-03-14

我认为将属性绑定到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官方文档:

  • https://docs.spring.io/spring-boot/docs/current/reference/html/features.html#features.external-配置。类型安全配置属性。java bean绑定
  • https://docs.spring.io/spring-boot/docs/current/reference/html/features.html#features.external-配置。类型安全配置属性。启用带注释的类型
 类似资料: