springboot 读取配置 yml 文件

本文介绍了在Springboot中读取yml配置文件的两种方法:一是使用YamlPropertiesFactoryBean,二是通过原生Properties类加载。在第一种方法中,首先检查配置文件是否存在,然后创建YamlPropertiesFactoryBean实例并获取Properties对象读取属性;第二种方法则是直接使用Properties类加载classpath下的文件内容。

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

springboot 读取配置 yml 文件

方式一:
通过 YamlPropertiesFactoryBean 读取

    public static String readConfigurationFile(String fileName, String attribute) {
        // resources路径地址
        String resourcesPath = Thread.currentThread().getContextClassLoader().getResource("").getPath();

        // 判断配置文件是否存在
        boolean exist = FileUtil.exist(resourcesPath + fileName);

        if (exist) {
            // 读取配置文件
            YamlPropertiesFactoryBean yamlPropertiesFactoryBean = new YamlPropertiesFactoryBean();
            yamlPropertiesFactoryBean.setResources(new ClassPathResource(fileName));

            // 读取配置文件属性
            Properties properties = yamlPropertiesFactoryBean.getObject();
            return properties.getProperty(attribute);
        } else {
            System.out.println("配置文件不存在");
        }
        return null;
    }

方式二:
通过原生方式读取

    public static String readConfigurationFileOther(String fileName, String attribute) {
        Properties properties = new Properties();
        ClassPathResource classpathResource = new ClassPathResource(fileName);//该路径是相对于src目录的,即classpath路径
        try {
            InputStream fileInputStream = classpathResource.getInputStream();
            properties.load(fileInputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return properties.getProperty(attribute);
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值