Reputation: 732
I have set up my resources like this:
<bean id="messageSource"
class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basename">
<value>locale\\messages</value>
</property>
</bean>
My propertyFile:
battle.name=TestBattle
I would like to reach the text "TestBattle" when I use a bean:
<bean id="battlefield" class="com.mypackage.Battlefield" scope="prototype">
<constructor-arg index="0" value="battle.name" />
<constructor-arg index="1" ref="armies" />
</bean>
I want to refeer the message in the propertyFile in this line
<constructor-arg index="0" value="battle.name" />
Is there a way to do it without going into java using the
getMessage("battle.name",...
code in java?
Upvotes: 1
Views: 4606
Reputation: 10709
At least, you could use spel to do it.
for example
<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>
However it seems cumbersome if you have to translate many codes.
Other option is using a String
to String
PropertyEditor
to do the translation.
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;
}
}
And use the prefix i18n: to translate codes, ie
<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>
Upvotes: 2