Spring Boot通过注解读取配置文件,并解决读取配置文件中文乱码问题

本文介绍了如何在Spring Boot中使用注解读取配置文件`config.properties`,并详细讲解了如何处理配置文件中文乱码问题。通过在`PluginConfig.java`中使用`@ConfigurationProperties`和`@PropertySource`注解,以及在`ConfigController.java`中进行测试。当`@PropertySource`未指定`encoding="utf-8"`导致中文乱码时,建议使用记事本将配置文件另存为UTF-8编码来解决问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在编写Spring boot项目时,注解帮助我们简化了大量的代码量。

现在给大家介绍一个通过注解读取配置文件的例子。

配置文件:resources/config.properties

内容如下:

conf.plugin.key1=小米
conf.plugin.key2=小明

编写配置文件读取类:PluginConfig.java

@Component
@ConfigurationProperties(prefix = "conf")
@PropertySource(value = "classpath:config.properties",encoding = "utf-8")
@Data
public class PluginConfig {
    private Map<String, String> plugin = new HashMap<>();

}

详解:

1)@ConfigurationProperties,它可以把同类的配置信息自动封装成实体类

2)@PropertySource,加载指定的属性文件,可以指定编码格式(可选)

注意:

1) @PropertySource注解中不设置encoding="utf-8",当遇到中文时,将会出现中文乱码问题。

2)在进行上类的编写时,Map<String,String> plugin,这个变量名一定要为plugin,和配置文件中的文本设置保持一致:

conf.plugin.key1=小米

编写ConfigController.java

package com.casic304.porter.controller;

import com.casic304.porter.core.PluginConfig;
import com.casic304.porter.core.PluginObject;
import com.casic304.porter.plugin.PluginReader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @author fanyanyan
 * @Title: ConfigController
 * @date 2019/5/23 16:45
 */
@Controller
@RequestMapping("/test")
public class ConfigController {
    final static String READER_RESULT = "ok";
    @Autowired
    private PluginConfig plugin;

    @GetMapping("/config")
    @ResponseBody
    public String config() {
        return plugin.getPlugin().toString();
    }
}

进行测试:

 

如果设置了encoding="utf-8"后依然出现中文乱码问题:

可用如下方法解决:

1)用记事本将配置文件打开

2)另存为配置文件,修改编码为:UTF-8

到此,Spring boot 通过注解读取配置文件的方法写完了,希望对您有用!

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值