简体   繁体   中英

Java Properties - how to create dynamic properties

Im trying to create a Java properties file in the format

api.base=http://example.com/api
api.get_posts=<dynamic_value_for_api_base>/get_posts

Im not quite sure if its possible, but I've definitely seen it done before (although it might have been done using Ant). Is there something I can do in this instance, in the properties file, without having to do it programmatically in Java?

Thanks Stephen

In Java you can have your own property file(s). You can also modify them at runtime (this does not seem to be what you are after, but I think it is handy to know it). You can take a look at this link for more information.

There is no real way of changing this dynamically in the file, besides editing the file through code.

I think it'll be better to just put:

api.get_posts=get_posts

and the dynamic part you would add in code itself.

What you would have seen would be an ant or maven filter. It is possible to have variables set at build time using this.

What your are talking about doesn't occur in the resource loaders that would read the propery files with out code in place.

Additionally ofcourse if you are writing the java to read the property to implement pattern matching to support this.

No one bothers usually as it is easier to either do it at build time with filters and mvn or ant or just write the code not to need redundant configuration blocks that would benefit from dynamic content.

There are some methods in Struts that do this very thing. I believe it is in the ActionMessage class. We wrote our own and it could be hooked up to a property file object quite easily:

public static String addCustomText(String message, List values) {
    if (CollectionUtils.isEmpty(values)) {
        return message;
    }
    String temp = message;
    for (int i = 0; i < values.size(); i++) {
        temp = StringUtils.replace(temp, "{" + i + "}", StringUtils.trimToEmpty((String) values.get(i)));
    }
    return temp;
}

So you could write a property file accessor and then use this method to swap out {0} and such.

If your're looking for a way to override a property which is present inside a properties file like property name=property value.

You can overwrite this property by overwriting the file itself during run-time .

This means that previously existing file is completely over-written and this new file takes its place.

So,any properties which might have existed previously are not there any more. Therefore, some care needs to be taken while doing this. Take a look at this to see how this can be achieved How do I create a file and write to it in Java?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM