I am trying to retrieve value from application.yml. The final line below is showing kafkaConfig as null, and cannot read. How do I setup the Kafka Config and code properly, to read from the json file? We are using @Data instead of 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
}
Resource: https://codingnconcepts.com/spring-boot/spring-configuration-properties-using-yml/
CodePudding user response:
I think the recommended way of binding properties to pojos is to use the @EnableConfigurationProperties
annotation like so:
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;
}
// [...]
}
Refer to the official Spring Documentation for further details:
- https://docs.spring.io/spring-boot/docs/current/reference/html/features.html#features.external-config.typesafe-configuration-properties.java-bean-binding
- https://docs.spring.io/spring-boot/docs/current/reference/html/features.html#features.external-config.typesafe-configuration-properties.enabling-annotated-types
CodePudding user response:
Add one more annotation @EnableConfigurationProperties
on the class KafkaConfig
KafkaConfig.java
@Configuration
@EnableConfigurationProperties // new added annotation
@ConfigurationProperties("kafka")
@Data
public class KafkaConfig {
private String topic;
private String event;
}
CodePudding user response:
@ComponentScan(basePackages ="PATH" )
PATH: the package path you want it to look for
@ComponentScan(basePackages ="PATH" )
@Configuration
@Import(value = {
KafkaProducerBeans.class
})
public class AppConfig{
}