在编写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 通过注解读取配置文件的方法写完了,希望对您有用!