可以使用 Spring Boot 提供的 ResourceLoader 类来获取根目录下的所有 properties 文件。

示例代码如下:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.util.StringUtils;

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

@SpringBootApplication
public class Application {

    @Autowired
    private ResourceLoader resourceLoader;

    public static void main(String[] args) {
        // 扫描所有properties文件
        List<Properties> propertiesList = getPropertiesList('classpath*:/application*.properties');
        // 处理properties文件
        for (Properties properties : propertiesList) {
            // TODO: 处理逻辑
        }
    }

    /**
     * 获取资源列表
     *
     * @param locationPattern 资源路径匹配模式
     * @return 资源列表
     */
    private static List<Resource> getResources(String locationPattern) {
        List<Resource> resources = new ArrayList<>();
        ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        try {
            Resource[] resArr = resolver.getResources(locationPattern);
            for (Resource resource : resArr) {
                resources.add(resource);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return resources;
    }

    /**
     * 获取properties文件列表
     *
     * @param locationPattern 资源路径匹配模式
     * @return properties文件列表
     */
    private static List<Properties> getPropertiesList(String locationPattern) {
        List<Properties> propertiesList = new ArrayList<>();
        List<Resource> resources = getResources(locationPattern);
        for (Resource resource : resources) {
            Properties properties = new Properties();
            try {
                properties.load(resource.getInputStream());
                propertiesList.add(properties);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return propertiesList;
    }
}

在上面的示例代码中,getResources 方法用于获取资源列表,getPropertiesList 方法用于获取 properties 文件列表。在 main 方法中,我们使用 classpath*:/application*.properties 作为资源路径匹配模式,获取所有以 application 为前缀的 properties 文件。获取到 properties 文件列表后,可以根据需要进行处理。

SpringBoot 获取根目录下所有 Properties 文件

原文地址: http://www.cveoy.top/t/topic/ol8j 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录