目录
国际化配置测试
测试
测试:
自定义一个MessageSource类型的bean
java
import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.ResourceBundleMessageSource;
/**
* @Author mubi
* @Date 2025/1/12 15:15
*/
@Configuration
public class I18nMessageSource {
@Bean(name = "myMessageSource")
public MessageSource messageSource() {
ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
messageSource.setBasenames("i18n.messages");
messageSource.setDefaultEncoding("UTF-8");
return messageSource;
}
}
SpringApplicationUtil工具类
java
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
@Component
public class SpringApplicationUtil implements ApplicationContextAware {
private static ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
SpringApplicationUtil.applicationContext = applicationContext;
}
public static Object getBean(String beanName){
return applicationContext.getBean(beanName);
}
public static List<String> getAllBeanNames(){
String[] arr = applicationContext.getBeanDefinitionNames();
if(arr == null || arr.length == 0){
return new ArrayList<>();
}
return Arrays.stream(arr).collect(Collectors.toList());
}
}
MessageUtls工具类
java
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
public class MessageUtls {
public static String message(String code, Object... args) {
MessageSource messageSource = (MessageSource) SpringApplicationUtil.getBean("myMessageSource");
return messageSource.getMessage(code, args, LocaleContextHolder.getLocale());
}
}
配置
resources下按照配置
java
test.message=just test message
java
test.message=仅测试消息
国际化原理
自定义的bean
java
@Bean(name = "myMessageSource")
public MessageSource messageSource() {
ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
messageSource.setBasenames("i18n.messages");
messageSource.setDefaultEncoding("UTF-8");
return messageSource;
}
ResourceBundleMessageSource
直接自定义的ResourceBundleMessageSource入手