MessageSourceAccessor的用法
时间: 2024-05-16 15:16:54 浏览: 189
MessageSourceAccessor是Spring框架提供的一个国际化消息处理工具,它可以方便地获取不同语言的消息文本。通常在Web应用中,我们需要根据用户的语言偏好来显示对应的消息文本,这时就可以使用MessageSourceAccessor来实现。
以下是MessageSourceAccessor的基本用法:
1. 配置MessageSource
在Spring配置文件中,需要配置一个MessageSource bean。
```xml
<bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basename" value="classpath:messages" />
<property name="defaultEncoding" value="UTF-8" />
<property name="cacheSeconds" value="3600" />
</bean>
```
其中,basename属性指定了消息资源文件的前缀,比如messages.properties,messages_en_US.properties等;defaultEncoding属性指定了消息文本的编码方式;cacheSeconds属性指定了消息缓存时间,单位为秒。
2. 获取MessageSourceAccessor
在需要使用消息文本的地方,通过依赖注入或者ApplicationContext.getBean()方法来获取MessageSourceAccessor对象。
```java
@Autowired
private MessageSourceAccessor messageSource;
```
或
```java
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
MessageSourceAccessor messageSource = new MessageSourceAccessor(context.getMessageSource());
```
3. 获取消息文本
调用MessageSourceAccessor的getMessage()方法来获取指定语言的消息文本。
```java
String message = messageSource.getMessage("hello.world", new Object[] {"张三"}, Locale.CHINA);
```
其中,第一个参数为消息文本的key,第二个参数为替换消息文本中占位符的参数,第三个参数为指定的语言环境。
如果没有找到对应的消息文本,会返回默认的消息文本,即key本身。
阅读全文
相关推荐









