SpringBoot国际化失败的原因,切换中英文无效

现象:在尝试国际化的过程中,无法切换中英文,一直显示中文。

原因:在配置类中,配置LocaleResolver时,方法名出错

@Configuration
public class SpringBootWebConfig implements WebMvcConfigurer {

    @Bean
    public LocaleResolver myLocaleResolver(){
        return new MyLocaleResolver();
    }
}

就是MyLocaleResolver这里出错,名称必须是localeResolver,否则SpringBoot根本不会调用MyLocaleResolver()。

@Configuration
public class SpringBootWebConfig implements WebMvcConfigurer {

    @Bean
    public LocaleResolver localeResolver(){
        return new MyLocaleResolver();
    }
}

说到底还是对SpringBoot的理解不够深刻啊。。。Bean注解注册组件时,组件的默认名字就是方法名字。如果名字不是localeResolver,SpringBoot也就找不到localeResolver这样一个bean,相当于白注册了。(不确定对不对,如果有误欢迎指正)

  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
以下是在Spring Boot项目中实现中英文切换的步骤: 1. 设置项目编码UTF8 ```java 在项目配置文件application.properties或application.yml中添加以下配置: spring.http.encoding.charset=UTF-8 spring.http.encoding.enabled=true spring.http.encoding.force=true ``` 2. 在resources目录下新建i18n文件夹及语言配置文件 ```shell 在src/main/resources目录下新建i18n文件夹,并在该文件夹下创建多个语言配置文件,例如: messages.properties(默认语言配置文件) messages_en.properties(英文语言配置文件) messages_zh.properties(中文语言配置文件) ``` 3. 指出国际化相关文件的位置 ```java 在项目配置文件application.properties或application.yml中添加以下配置: spring.messages.basename=i18n/messages ``` 4. 展示页面 ```html 在HTML页面中使用Thymeleaf模板引擎实现国际化,例如: <p th:text="#{hello}"></p> ``` 5. 使用按钮切换中英文页面 5.1 新建html页面 ```html 在HTML页面中添加切换语言的按钮,例如: <button onclick="window.location.href='?lang=en'">English</button> <button onclick="window.location.href='?lang=zh'">中文</button> ``` 5.2 实现LocaleResolver 接口 ```java 创建一个自定义的LocaleResolver实现类,用于根据请求参数或其他方式切换语言,例如: public class MyLocaleResolver implements LocaleResolver { // 实现切换语言的逻辑 } ``` 5.3 放入Bean ```java 将自定义的LocaleResolver实现类放入Spring容器中,例如: @Bean public LocaleResolver localeResolver() { return new MyLocaleResolver(); } ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值