When we need to read the variables of the configuration file in the project, we often encounter the problem of reading Chinese garble:

English characters do not have this problem.

The reasons for this problem are as follows:

The default code used by SpringBoot to load a configuration file is ISO_8859_1.

Please refer to:

Eericzeng. Making. IO / 2019/06/29 /…

Then, can’t we just modify the encoding format of IDEA to UTF-8?

This approach seems to solve the problem, but not completely solved, there will still be the problem of garbled code.

So the first rule we need to follow is: try to avoid Chinese configuration in the configuration file,

When we have to configure Chinese data, we can use the following solution:

Read the Chinese configuration in Properties using the @propertysource annotation.

Below is the demo:

Create a new configuration file: xxx.properties. The name must be different from application.properties.

Create a new class to receive configuration:

@Data
@Component
@PropertySource(value = "classpath:chinese.properties", encoding="UTF-8")
// Specify the prefix to read the configuration
@ConfigurationProperties(prefix = "com.example.demo")
public class Properties {
    private String name;
    private Integer age;
    private String address;
}
Copy the code

Use:

The @autowired reference

This will load the Chinese configuration correctly.

@ConfigurationProperties can also load YML configurations without garbled characters.

How do I obtain configuration data in YML?