Issue
In a Spring Boot application, I would like to be able to declare a list of my domain objects in my application.properties
file and read them as a List<TheDomainObject>
as a Bean
.
For example, let's say I have the following in application.properties
:
com.application.person.john.name=John Smith
com.application.person.john.home-directory=/Users/john.smith
com.application.person.john.private-key-file=/Users/john.smith/.ssh/id_rsa
com.application.person.adam.name=Adam Bell
com.application.person.adam.home-directory=/Users/adam.bell
com.application.person.adam.private-key-file=/Users/adam.bell/.ssh/id_rsa
etc
I.e. I'd like to have properties for each person grouped under a key. I'd be able to add as many keys (people) as I like.
I would not need to reference these properties directly, but I'd like to declare a Domain object as follows (abbreviated):
class Person {
String id; (this would be the 'key', i.e. 'john', 'adam')
String name;
Path homeDirectory;
Path privateKeyFile;
// boilerplate
}
and then receive a List<Person>
through Configuration
. The more automatic the better, but I would be more than happy to implement builders or some additional converter logic if needed.
I can't find any documentation for this kind of thing, but I have seen it in log4j for example, where you can dynamically add logging properties for any package name, so it must be possible to at least retrieve those keys.
I know I can do this differently, for example by using a data.sql
import script, however in my case it would be very ideal to have this in a single properties file (or yaml) format.
Solution
Why don't you use id as an explicit property?
for example (yaml):
com:
application:
persons:
-
id: john
name: John Smith
home-directory: /Users/john.smith
-
id: adam
name: Adam Bell
home-directory: /Users/adam.bell
This would resolve in List<Person> persons;
Answered By - JavaBoy
Answer Checked By - Senaida (JavaFixing Volunteer)