Search code examples
javaspringspring-mvcproperties-file

Accessing attribute with argument from file.properties in Java class


Let me explain what I want to do:

I got a properties containing a property like this:

message=Hello {0}, welcome.

I'd like to access this property in a Java class using a String and set the parameter in that class.

I've already use fmt:message and fmt:param to display this kind of property in a JSP but I want to manipulate it in a Java object now (I already know how to inject a property into the class).

Any idea on how to do this?


Solution

  • You can use java.util.ResourceBundle and java.text.MessageFormat Some examples

    private String getString( String bundle, String key, String defaultValue, Object... arguments ){
        String result = ResourceBundle.getBundle( bundle ).getString( key );
        if ( result == null ){
            result = defaultValue;
        }
        if ( arguments.length > 0 && result != null ){
            result = MessageFormat.format( result, arguments );
        }
        return result; 
    }