SpringBoot 面试题, 如何在 Spring Boot 应用中实现国际化i18n?
SpringBoot 面试题, 如何在 Spring Boot 应用中实现国际化i18n?
QA
Step 1
Q:: 如何在 Spring Boot 应用中实现国际化(i18
n)?
A:: 在 Spring Boot 应用中实现国际化(i18
n),需要以下几个步骤:
1.
配置国际化消息资源文件:在 src/main/resources
目录下创建不同语言的消息文件,例如 messages.properties
(默认语言)、messages_en.properties
(英文)、messages_fr.properties
(法文)等。
2.
配置国际化 Bean:在配置类中添加 LocaleResolver
和 LocaleChangeInterceptor
Bean。
@Configuration
public class WebConfig extends WebMvcConfigurerAdapter {
@Bean
public LocaleResolver localeResolver() {
SessionLocaleResolver slr = new SessionLocaleResolver();
slr.setDefaultLocale(Locale.US); // 默认语言
return slr;
}
@Bean
public LocaleChangeInterceptor localeChangeInterceptor() {
LocaleChangeInterceptor lci = new LocaleChangeInterceptor();
lci.setParamName("lang"); // 参数名称
return lci;
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(localeChangeInterceptor());
}
}
3.
使用国际化消息:在需要显示国际化消息的地方使用 @Autowired
注入 MessageSource
,并使用 messageSource.getMessage()
方法获取相应的消息。
@Autowired
private MessageSource messageSource;
public String getGreeting(String name) {
Locale locale = LocaleContextHolder.getLocale();
return messageSource.getMessage("greeting", new Object[]{name}, locale);
}
4.
切换语言:通过 URL 参数 lang
切换语言,例如 http://localhost:8080?lang=fr
。
Step 2
Q:: 如何配置 Spring Boot 国际化文件的编码?
A:: 在 Spring Boot 应用中,默认情况下,国际化消息文件使用 ISO-8859-1 编码。如果需要使用 UTF-8
编码,可以在 application.properties
文件中进行配置:
spring.messages.basename=messages
spring.messages.encoding=UTF-8
Step 3
Q:: 如何在 Thymeleaf 模板中使用国际化消息?
A:: 在 Thymeleaf 模板中使用国际化消息非常简单,只需使用 #{}
语法。例如:
<p th:text="#{welcome.message}">Welcome message</p>
其中,welcome.message
是在国际化消息文件中定义的键。
Step 4
Q:: 如何测试 Spring Boot 应用中的国际化功能?
A:: 测试 Spring Boot 应用中的国际化功能可以通过以下几种方式:
1.
单元测试:编写单元测试,验证不同语言环境下的消息是否正确。
@RunWith(SpringRunner.class)
@SpringBootTest
public class InternationalizationTests {
@Autowired
private MessageSource messageSource;
@Test
public void testMessageSource() {
String message = messageSource.getMessage("greeting", new Object[]{"John"}, Locale.US);
assertEquals("Hello, John!", message);
message = messageSource.getMessage("greeting", new Object[]{"John"}, Locale.FRANCE);
assertEquals("Bonjour, John!", message);
}
}
2.
集成测试:通过模拟 HTTP 请求测试国际化功能。
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class InternationalizationIntegrationTests {
@Autowired
private TestRestTemplate restTemplate;
@Test
public void testGreetingInDifferentLanguages() {
ResponseEntity<String> response = restTemplate.getForEntity("/greeting?lang=fr", String.class);
assertEquals("Bonjour, John!", response.getBody());
response = restTemplate.getForEntity("/greeting?lang=en", String.class);
assertEquals("Hello, John!", response.getBody());
}
}