SpringBoot读取properties中文乱码解决方案

目录

一、问题描述

二、解决方案

2.1、网络上的解决办法

2.1.1、修改IDEA编码 

2.1.2、改为yml配置

2.1.3、读取时设置编码

2.2、重写资源加载类(个人推荐)


一、问题描述

由于业务需求需要在application.properties中配置一个带有中文字符串的参数,注入到业务类中,但是发现注入的中文是乱码的。大概情况如下所示:

package com.cnstar.test;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

/**
 * cnstar单元测试
 * @author cnstar
 **/
@SpringBootTest(classes = TestApplication.class)
@RunWith(SpringRunner.class)
public class CnstarTest {

    @Value("${name}")
    private String name;

    @Test
    public void test1() {
        System.out.println("中文内容:" + name);
    }
}

打印输出结果:

SpringBoot读取properties中文乱码解决方案_第1张图片

二、解决方案

2.1、网络上的解决办法

遇到问题首先想到网络上找解决方案,网络上的解决办法基本一致,概括为以下三种。 

2.1.1、修改IDEA编码 

在IDEA中将所有的编码设置为UTF-8,同时勾上Transparent native-to-ascii conversion的选项,然后重新创建application.properties的文件。

SpringBoot读取properties中文乱码解决方案_第2张图片

运行结

你可能感兴趣的:(spring,boot,spring,java)