Springboot 国际化通过Header中Accept-Language的值切换语言实战与AcceptHeaderLocaleResolver源码解析
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Bean
public LocaleChangeInterceptor localeChangeInterceptor() {
LocaleChangeInterceptor localeChangeInterceptor = new LocaleChangeInterceptor();
localeChangeInterceptor.setParamName("lang");
return localeChangeInterceptor;
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(localeChangeInterceptor());
}
}
这段代码定义了一个配置类WebConfig
,实现了WebMvcConfigurer
接口,并注册了一个LocaleChangeInterceptor
拦截器,该拦截器会根据请求中名为lang
的参数改变应用程序的语言环境。这是Spring Boot应用程序中常用的一种实现国际化的方法。
评论已关闭