Spring Boot 3.x 特性-国际化
    		       		warning:
    		            这篇文章距离上次修改已过426天,其中的内容可能已经有所变动。
    		        
        		                
                在Spring Boot 3.x中,我们可以使用MessageSource来实现应用程序的国际化(i18n)。以下是一个简单的示例,展示如何添加国际化支持:
- 在
src/main/resources目录下创建多个属性文件,命名为messages_xx.properties,其中xx是特定的语言代码(例如:messages_en.properties,messages_fr.properties)。 
messages_en.properties (英文):
greeting=Hello, {0}!messages_fr.properties (法文):
greeting=Bonjour, {0}!- 配置
MessageSourcebean。 
@Configuration
public class I18NConfig {
 
    @Bean
    public MessageSource messageSource(ResourceLoader resourceLoader) throws IOException {
        ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
        messageSource.setBasename("messages");
        messageSource.setDefaultEncoding("UTF-8");
        return messageSource;
    }
}- 使用
MessageSource进行国际化。 
@RestController
public class GreetingController {
 
    private final MessageSource messageSource;
 
    public GreetingController(MessageSource messageSource) {
        this.messageSource = messageSource;
    }
 
    @GetMapping("/greeting")
    public String greeting(@RequestParam(name = "name", defaultValue = "World") String name, Locale locale) {
        return messageSource.getMessage("greeting", new Object[]{name}, locale);
    }
}当你访问/greeting时,你可以通过请求参数name来设置用户的名字,并且可以通过语言环境(例如:Locale.US或Locale.FRANCE)来获取对应语言的问候。
评论已关闭