springboot 读取配置 yml 文件

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);
    }

你可能感兴趣的:(java,spring,boot,spring)