Springboot-application.properties中文乱码问题

设置application.properties为utf-8

UTF-8,这样在windows和linux服务器中查看配置文件都能正常显示中文。否则可能中文无法正常显示。
在这里插入图片描述
application.properties中配置如下:

demo.to-who=张三

读取配置的中文

@RestController
public class TestController {

    @Value("${demo.to-who}")
    private String toWho;

    @RequestMapping("/test2")
    public Object test2() throws UnsupportedEncodingException {
        System.out.println(toWho);
        System.out.println(new String(toWho.getBytes("iso8859-1")));
        System.out.println(new String(toWho.getBytes("iso8859-1"), "utf-8"));
        return null;
    }
}

结果打印

需要将数据编码从iso8859-1转为utf-8才可正常使用。

å¼ ä¸‰
张三
张三

分析

源码中

private static class CharacterReader implements Closeable {
    // 其他代码省略
    CharacterReader(Resource resource) throws IOException {
      this.reader = new LineNumberReader(new InputStreamReader(
          resource.getInputStream(), StandardCharsets.ISO_8859_1));
    }
    // 其他代码省略
}

也就是说不论application.properties文件被设置为哪种编码格式,最终还是以ISO-8859-1的编码格式进行加载。

而yml/yaml默认以UTF-8加载;

参考:SpringBoot使用@Value读取.properties中文乱码及解决方法

  • 4
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
在Spring Boot项目中,如果application.properties文件中的中文出现码,这可能是因为Spring Boot默认使用的编码方式是ISO_8859_1。这意味着无论我们将application.properties文件保存为何种编码方式,最终它都会以ISO_8859_1的编码方式加载。 当我们的配置文件中包含中文字符时,如果不使用正确的编码方式进行设置,就会导致中文字符在加载时出现码。为了解决这个问题,我们可以使用UTF-8编码方式来保存和加载application.properties文件。可以在项目的启动类上添加如下注解来指定编码方式: ```java @SpringBootApplication public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } @PostConstruct public void init() { // 设置Spring Boot的编码方式为UTF-8 Charset charset = Charset.forName("UTF-8"); Charset.setDefaultCharset(charset); } } ``` 通过这种方式,我们可以确保application.properties文件中的中文字符能够正确加载,避免出现问题。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [如何处理从application.properties配置文件获取的汉字问题](https://blog.csdn.net/u013232219/article/details/122270606)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] - *2* *3* [application.properties中文码的解决方案](https://blog.csdn.net/qq_43753724/article/details/122351883)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值