Using ConfigurationProperties to build Java POJO Map

Viewed 473

I have below some of the properties in the HashMap as key value pair

topic1.topicname =testTopic1
topic1.listenerid=id1
topic1.max.poll.records=5
topic2.topicname =testTopic2
topic2.listenerid=id2
topic2.max.poll.records=5

And I want to convert the above key value pair into java pojo configuration properties as below

Map<String, CustomKafkaListenerProperty> props;

with key as topic1 and topic2, and value as corresponding CustomKafkaListenerProperty pojo

the attributes in CustomKafkaListenerProperty Pojo as below

private String topicname;
private String listenerId;
private String maxPollRecords;

Need help on how to do this with spring @ConfigurationProperties

1 Answers

If you can "prepend something" in front of your properties and "flatten" max.poll.records like:

foo.bar.topic1.topicname =testTopic1
foo.bar.topic1.listenerid=id1
foo.bar.topic1.max-poll-records=5
foo.bar.topic2.topicname =testTopic2
foo.bar.topic2.listenerid=id2
foo.bar.topic2.max-poll-records=5

Then (it's a 14-liner,) we can model them like:

@Getter
@Setter
@ToString
@ConfigurationProperties("foo")
public class MyProperties { // must be public! regarding constructors, read https://docs.spring.io/spring-boot/docs/current/reference/html/features.html#features.external-config.typesafe-configuration-properties.java-bean-binding

  Map<String, CustomKafkaListenerProperty> bar;

}

..and:

@Getter
@Setter
@ToString
class CustomKafkaListenerProperty { // can be non: pulic/static/nested
    String topicname;
    String listenerId;
    String maxPollRecords;
}

... enable them:

@SpringBootApplication
// when they are in a custom file: @PropertySource(("classpath:/com/example/some.properties"))
@EnableConfigurationProperties(MyProperties.class)
public class SpringApp { ...

So the test:

@SpringBootTest
class SpringAppTests { 

  @Autowired
  MyProperties props;

  @Test
  void contextLoads() {
    System.out.println(props);
    assertNotNull(props);
  }
}

...will pass! ...and give us following output:

MyProperties(bar={
  topic2 = MyProperties.CustomKafkaListenerProperty(topicname=testTopic2, listenerId=id2, maxPollRecords=5),
  topic1 = MyProperties.CustomKafkaListenerProperty(topicname=testTopic1, listenerId=id1, maxPollRecords=5)}
)

(originally unformatted)

Problems:

  • We have to pre-pend the properties as they are. (i see no other way (yet))

  • We have to change max.poll.records to max-poll-records (kebab-case).

Related