获取SpringBoot配置文件属性值方式

本文介绍了三种在SpringBoot中获取配置文件属性值的方式:1)使用@Value注解;2)通过Properties工具类加载;3)利用JDK的ResourceBundle类。详细步骤和示例代码展示了如何操作,帮助开发者更好地理解和使用配置文件。

获取SpringBoot配置文件属性值方式

1. 注解方式

@Value

2. Properties的工具类获取方式

import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.support.EncodedResource;
import org.springframework.core.io.support.PropertiesLoaderUtils;

import java.io.IOException;
import java.util.Properties;

/**
 * 配置文件工具类
 * @author wyp
 */
@Slf4j
public class PropertiesUtil {
    /**
     * 读取配置文件
     * @param location 配置文件路径
     * @return Properties
     */
    public static Properties getProperties(String location){
        try {
            log.info("正在加载配置资源\"{}\"",location);
            return PropertiesLoaderUtils.loadProperties(new EncodedResource(new ClassPathResource(location), "utf-8"));
        } catch (IOException e) {
            log.error("加载配置资源\"{}\"加载失败!",location);
            e.printStackTrace();
            return null;
        }

    }
}

在resource目录下创建properties文件夹,新增file-config.properties文件

file.img.suffixList=.jpg,.png,.gif,.jpeg

编写测试类测试:

import cn.xc.util.PropertiesUtil;
import org.junit.jupiter.api.Test;
import java.util.Properties;

public class T {
    @Test
    void t(){
        //加载配置文件
        Properties properties = PropertiesUtil.getProperties("properties/file-config.properties");
        if (properties != null){
            //获取配置文件中属性值
            String hello = properties.getProperty("file.img.suffixList");
            System.out.println(hello);
        }
    }
}

运行结果:

16:56:43.181 [main] INFO cn.xc.util.PropertiesUtil - 正在加载配置资源"properties/file-config.properties"
.jpg,.png,.gif,.jpeg

3. JDK自带ResourceBundle类读取配置文件

ResourceBundle类是java提供的一个读取properties文件(配置文件)的一种方法。

资源文件必须在classpath下(resource),如果是web项目需放在WEB-INF\classes\目录下。

application.properties

hello=123abc

ResourceBundleTest.java

import java.util.ResourceBundle;

public class ResourceBundleTest {
    public static void main(String[] args) {
        //fileName.properties,后缀必须省略
        String fileName = "application";
        ResourceBundle resourceBundle = ResourceBundle.getBundle(fileName);
        System.out.println(resourceBundle.getString("hello"));
        //区分大小写
        System.out.println(resourceBundle.getString("Hello"));
    }
}

运行结果:

123abc
Exception in thread "main" java.util.MissingResourceException: Can't find resource for bundle java.util.PropertyResourceBundle, key Hello
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小辰~

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值