简体   繁体   中英

spring - How to set List of java.util.Locale in Spring XML?

How can I configure list of java.util.Locale in Spring XML?

This is what I tried (which obviously didn't work..):-

<bean
    class="x.y.z.CommandBean"
    scope="prototype">
    <property name="locales">
        <list value-type="java.util.Locale">
            <value>Locale.US</value>
            <value>Locale.FR</value>
        </list>
    </property>
</bean>

Exception :-

 org.springframework.beans.TypeMismatchException: Failed to convert value of type 'java.lang.String' to required type 'java.util.Locale';

Also, is there any way I can move the locale as comma separated values in a .properties file?

Try this,

 <property name="locales">
        <list value-type="java.util.Locale">
            <value>java.util.Locale.US</value>
            <value>java.util.Locale.FR</value>
        </list>
    </property>

In your class,

private List<Locale> locales;

    public List<Locale> getLocales() {
        return locales;
    }


    public void setLocales(List<Locale> locales) {
        this.locales = locales;
    }

Specifying the values as

<value>java.util.Locale.US</value>
<value>java.util.Locale.FR</value>

should do the trick. Getting them from a properties value seems a bit more work.

You could specify them like

my.app.locales=en_US,de_DE

configuring

<bean 
    class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="location">
        <value>file:./config.properties</value>
    </property>
</bean>
<bean
    class="x.y.z.CommandBean"
    scope="prototype">
    <property name="locales">
        <bean class="org.springframework.util.StringUtils" factory-method="tokenizeToStringArray">
            <constructor-arg type="java.lang.String" value="${my.app.locales}"/>
            <constructor-arg type="java.lang.String" value=","/>
        </bean>
    </property>
</bean>

and then you would need

import org.apache.commons.lang3.LocaleUtils;

public void setLocales(String[] localeStrings) {
   List<Locale> locales = new ArrayList<Locale>(localeStrings.length);
   for (String localeName: Arrays.asList(localeStrings)) {
      locales.add(LocaleUtils.toLocale(localeName));
   }
   this.locales = locales;
}

this is a bit gludgy though. As an alternative, you could define a wrapper class that does the conversion above, and wire that as a bean. Then hook your class to that bean.

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