@Component("springUtils")
@Lazy(false)
public class SpringUtils implements ApplicationContextAware, DisposableBean {
/** applicationContext */
private static ApplicationContext applicationContext;
/**
* 不可实例化
*/
private SpringUtils(){
}
@Override
public void destroy() throws Exception {
applicationContext = null;
}
@Override
public void setApplicationContext(ApplicationContext applicationContext)
throws BeansException {
SpringUtils.applicationContext = applicationContext;
}
/**
* 获取applicationContext
*
* @return applicationContext
*/
public static ApplicationContext getApplicationContext() {
return applicationContext;
}
/**
* 获取实例
*
* @param name
* Bean名称
* @return 实例
*/
public static Object getBean(String name) {
Assert.hasText(name);
return applicationContext.getBean(name);
}
/**
* 获取实例
*
* @param name
* Bean名称
* @param type
* Bean类型
* @return 实例
*/
public static <T> T getBean(String name, Class<T> type) {
Assert.hasText(name);
Assert.notNull(type);
return applicationContext.getBean(name, type);
}
/**
* 获取国际化消息
*
* @param code
* 代码
* @param args
* 参数
* @return 国际化消息
*/
public static String getMessage(String code, Object... args) {
LocaleResolver localeResolver = getBean("localeResolver", LocaleResolver.class);
Locale locale = localeResolver.resolveLocale(null);
return applicationContext.getMessage(code, args, locale);
}
}
test.properties 添加配置文件信息
#配置国际化
locale=zh_TW
url_escaping_charset=UTF-8
message.cache_seconds=3600
message.common_path=/WEB-INF/language/message
applicationContext.xml 添加扫描SpringUtils所在包
<!-- 扫描util -->
<context:component-scan base-package="com.test.util"/>
applicationContext.xm
<!-- 配置国际化 -->
<bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="cacheSeconds" value="${message.cache_seconds}" />
<property name="useCodeAsDefaultMessage" value="true" />
<property name="basenames">
<list>
<value>${message.common_path}</value>
</list>
</property>
</bean>
<bean id="localeResolver" class="org.springframework.web.servlet.i18n.FixedLocaleResolver">
<property name="defaultLocale" value="${locale}" />
</bean>
在/WEB-INF/language下添加国际化语言文件
message_zh_CN
demo.test=\u8303\u56F4
message_zh_TW
demo.test=\u7BC4\u570D
现在即可在jsp中输出国际化消息了
alert("<%=SpringUtils.getMessage("demo.test")%>");
修改test.properties中locale为zh_CN即可输出简体中文信息