SpringBoot @PropertySource读取自定义properties文件

方法一:@PropertySource + @Value

首先准备一个properties文件,在resources文件夹下即可

 

 

 在properties文件中写下自己需要使用的key-value

 

 

 在需要调用这个key的类中,通过@PropertySource 注解引入config.properties,通过@Value(${keyName})的形式调用value值

@Component
@PropertySource(value = "classpath:config.properties", encoding = "UTF-8")
public class XxClassName{

    @Value("${error_ip}")
    private String ipErrorInfo;

    public void showErrorIp(){
        System.out.println(ipErrorInfo);
    }
}
    
【value = "classpath:config.properties"】
通过使用classpath可以访问到任意位置的config.properties,不再需要写完整的相对路径

【encoding="UTF-8"】
通过指定编码,可以避免读取中文value值时造成的乱码
posted @ 2021-01-27 14:46  代码羡  阅读(611)  评论(0编辑  收藏  举报