oblac / jodd

Jodd! Lightweight. Java. Zero dependencies. Use what you like.
https://jodd.org
BSD 2-Clause "Simplified" License
4.06k stars 724 forks source link

populate nested beans directly #207

Closed mbjelac closed 9 years ago

mbjelac commented 9 years ago

When a single properties map contains multiple "sections", for example a http section

http.port=10101
http.address=localhost
http.pool=30

it would be handy to be able to populate a bean with a section, for the above example, a HttpConfig bean

class HttpConfig {
    public int port;
    public String address;
    public int pool;
}

could be populated with

BeanUtils.populate(httpConfig, properties, "http").

Currently the only way to populate such beans is to create a "root" property bean

class RootConfig {
    public HttpConfig http;
}
igr commented 9 years ago

Again, great idea!

igr commented 9 years ago

Me again asking a question :) Isn't this what you actually want?

BeanUtil.populateBean(httpConfig, (Map) properties.get("http"));

You see, i kind of like this better then this:

BeanUtil.populateBean(httpConfig, properties, "http");

because map.get("name") can be anything and not always a map; and its therefore kind of vague. Moreover, you can do something like:

Map values = (Map) BeanUtil.getProperty(properties, "http.inner");
BeanUtil.populateBean(httpConfigInner, values);

I know it is not one liner, but the functionality is there. Wdyt?

mbjelac commented 9 years ago

aha, i wasn't aware that BeanUtil.getProperty does that - so basically it extracts a sub-map from a map based on the prefix? if you do BeanUtil.getProperty(properties, "http.inner"); do the keys in the resulting map have the http.inner prefix?

igr commented 9 years ago

Oopps sorry, that is not true what i've written.... I mixed this with the Props tool. Give me a sec to write what I ment :)))

igr commented 9 years ago

Ok here am I again, sorry for confusion.

BeanUtil is not aware of property names; so in its world it is the same if you have property named "foobar" or "foo.bar" - this is all the same to it.

However, this seems to be task for Jodd Props that is properties on steroids. Please give me some time to explore the options, as we already have something almost like you need :)

igr commented 9 years ago

Ok, after last commits, you can do this like:

Props props = new Props();
props.load(data);   // load props from Properties or directly from a file

Map innerMap = props.innerMap("http");
HttpConfig httpConfig = new HttpConfig();
BeanCopy.fromMap(innerMap).toBean(httpConfig).copy();

As said above, BeanUtil is unaware of the java properties syntax. For this we do have the Jodd Props tool - the powerful properties replacement. You may use it instead of regular java properties.

I hope you understand and that we can close this issue now ;)