简体   繁体   中英

Using Locale from Resource Bundle in Java Spring

I'm learning to use resouce bundle for printing locale-dependent messages in my project.

application.xml:

<bean class="org.springframework.context.support.ResourceBundleMessageSource">
    <property name="basename" value="ru.bpc.svat.svnr.integration.banking.messages" />
</bean>
<bean class="ru.bpc.svat.svnr.integration.banking.application.SpringContextMessageFactory"  />

Directory src\\main\\resources\\ru\\bpc\\svat\\svnr\\integration\\banking contains files:

messages.properties
messages_ru.properties
messages_ru_RU.properties

each having line:

test = testmessage

In my test class I get an instance of message factory and try to get a message:

@Autowired private MessageFactory messageFactory;
...
messageFactory.getMessage("test", new Object[]{}, Locale.getDefault());

And then I get an exception:

No message found under code 'test' for locale 'ru_RU'.

What's wrong with it? This might be a foolish question, but it's my first experience. Thank you for your answers.

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

</beans>

finally use SpringContext context.getMessage() method read your value.

Note: Assume your properties files are located at “resources\\locale\\customer\\” folder.as mentioned in value tag above. Basically those files needs to be in class-path of your project.

Let me know if it solves your problem, then accept my answer!

如果将文件直接放置到src / main / resources中(而不是src / main / resources的子目录中,该怎么办?)只是一个想法。通常,如果文件在类路径中,该文件应该可以找到。

Try to replace:

<bean class="org.springframework.context.support.ResourceBundleMessageSource">
    <property name="basename" value="ru.bpc.svat.svnr.integration.banking.messages" />
</bean>

on

<bean class="org.springframework.context.support.ResourceBundleMessageSource">
    <property name="basename" value="ru\bpc\svat\svnr\integration\banking\messages" />
</bean>

make sure that the path relative from your class. In other case put resource in src/main/resources and use classpath:\\ suffix

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