Skip to content

Instantly share code, notes, and snippets.

@thergbway
Last active October 13, 2016 22:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thergbway/5ce67a8c3c182b117838ecd7b9f80131 to your computer and use it in GitHub Desktop.
Save thergbway/5ce67a8c3c182b117838ecd7b9f80131 to your computer and use it in GitHub Desktop.
SPRING. INVERSION OF CONTROL. MESSAGE SOURCE
1. ApplicationContext это MessageSource
2. Чаще всего текущая реализация MessageSource является HierarchicalMessageSource, как например, ApplicationContext, то
ApplicationSource поддерживает идею иерархичности источников сообщений, те если мы не нашли сообщение в одном
MessageSource, то идем в другой и ищем там, те по иерархии вверх.
3. Возможные реализации MessageSource (точнее HierarchicalMessageSource):
* ResourceBundleMessageSource. Использует идеи ResourceBundle из JDK.
* ReloadableResourceBundleMessageSource. Более гибкий, можно читать из любого источника, а не только из classpath.
также позволяет динамически управлять загруженными сообщениями, например, перезагружать источники.
* StaticMessageSource. Позволяет программно создавать сообщения.
custom_message=Say hello to {0}!
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<!--Имя должно быть именно таким-->
<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="defaultEncoding" value="UTF-8"/>
<property name="basenames">
<list>
<value>ioc.message_source.main_messages</value>
<value>ioc.message_source.additional_messages</value>
</list>
</property>
</bean>
</beans>
package ioc.message_source;
import org.springframework.context.MessageSource;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
ClassPathXmlApplicationContext cx = new ClassPathXmlApplicationContext("ioc/message_source/context.xml");
MessageSource messageSource = cx;//Note! Our context is MessageSource
String m1 = messageSource.getMessage("custom_message", new Object[]{"User"}, "Default_User", null);
String m2 = messageSource.getMessage("program.about", null, null);
String m3 = messageSource.getMessage("program.about", null, Locale.forLanguageTag("fr-FR"));
}
}
program.about=This program is awesome!
program.about=Programme très cool!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment