Spring消息源,bean XML中的getMessage?

时间:2014-06-20 21:59:49

标签: java spring

我已经设置了这样的资源:

<bean id="messageSource"
        class="org.springframework.context.support.ResourceBundleMessageSource">
        <property name="basename">
            <value>locale\\messages</value>
        </property>
</bean>

我的物业文件:

battle.name=TestBattle

当我使用bean时,我想找到“TestBattle”文本:

<bean id="battlefield" class="com.mypackage.Battlefield" scope="prototype">
    <constructor-arg index="0" value="battle.name" />
    <constructor-arg index="1" ref="armies" />
</bean>

我想在此行中的propertyFile中重新提供消息

<constructor-arg index="0" value="battle.name" />

有没有办法在不使用

进入java的情况下执行此操作
getMessage("battle.name",...

java中的代码?

1 个答案:

答案 0 :(得分:1)

至少,您可以使用spel来完成它。

例如

<bean id="messageSourceAccessor" class="org.springframework.context.support.MessageSourceAccessor">
    <constructor-arg ref="messageSource" />
</bean>

<bean id="battlefield" class="com.mypackage.Battlefield" scope="prototype">
    <constructor-arg index="0" value="#{messageSourceAccessor.getMessage('battle.name')}" />
    <constructor-arg index="1" ref="armies" />
</bean>

但是,如果你需要翻译许多代码,这似乎很麻烦。

其他选项是使用StringString PropertyEditor进行翻译。

public class MessageSourcePropertyEditor extends PropertyEditorSupport {

    private MessageSourceAccessor messageSourceAccessor;

    public MessageSourcePropertyEditor(MessageSource messageSource) {
        this.messageSourceAccessor = new MessageSourceAccessor(messageSource);
    }

    @Override
    public void setAsText(String text) throws IllegalArgumentException {
        String value = text;

        if (text.startsWith("i18n:")) {
            value = messageSourceAccessor.getMessage(text.substring(5));
        }

        setValue(value);
    }
}

public class MessageEditorRegistrar implements PropertyEditorRegistrar {

    private MessageSource messageSource;

    @Override
    public void registerCustomEditors(PropertyEditorRegistry registry) {
        registry.registerCustomEditor(String.class, new MessageSourcePropertyEditor(messageSource));

    }

    public MessageSource getMessageSource() {
        return messageSource;
    }

    public void setMessageSource(MessageSource messageSource) {
        this.messageSource = messageSource;
    }
}

并使用前缀 i18n:来翻译代码,即

<bean id="propertyEditorConfigure" class="org.springframework.beans.factory.config.CustomEditorConfigurer">
    <property name="propertyEditorRegistrars">
        <list>
            <bean class="message.MessageEditorRegistrar">
                <property name="messageSource" ref="messageSource" />
            </bean>
        </list>
    </property>
</bean>

<bean id="battlefield" class="com.mypackage.Battlefield" scope="prototype">
    <constructor-arg index="0" value="i18n:battle.name" />
    <constructor-arg index="1" ref="armies" />
</bean>