如何查找PropertySource对象的文件路径(如果存在)

Mat*_*t R 5 java spring spring-mvc spring-boot

public MyObject(Environment env) {
    for(Iterator<PropertySource<?>> it = ((AbstractEnvironment) env).getPropertySources().iterator(); it.hasNext(); ) {
        PropertySource<?> source = it.next();
        if (source instanceof MapPropertySource && source.getSource() instanceof Properties {
            //add new property
            //get path to property file if exists and save some new properties/override existing.
Run Code Online (Sandbox Code Playgroud)

请考虑上面的代码。我想知道是否有人可以向我建议一种很好的干净方法来检索PropertySource对象的文件路径或流。

在我的特定情况下,在我的环境中,有两个我感兴趣的PropertySource对象。一个是位于外部的文件,一个是内部文件。它们在我的SpringBootApplication类中定义为:-

@SpringBootApplication
@PropertySources({ 
    @PropertySource(value = { "classpath:internal.properties" }),
    @PropertySource(value = { "file:${application.properties}" }) })
public class MyApplication extends SpringBootServletInitializer {...
Run Code Online (Sandbox Code Playgroud)

PropertySource对象具有getName()方法,该方法看起来包含我需要的信息,但不是以友好的方式。

具有类路径的PropertySource上的getName显示:-

class path resource [internal.properties]
Run Code Online (Sandbox Code Playgroud)

具有文件路径的PropertySource上的getName显示:-

URL [file:C:/Dev/conf/application.properties]
Run Code Online (Sandbox Code Playgroud)

括号之间的信息几乎可用。文件一是有效的URL,而类路径不是。

一种解决方案是仅标记这些字符串并构建url字符串,因为我掌握了足够的信息。我可以做到这一点,如果没有更好的建议,我会做的。所以我想知道是否有人知道任何有用的Spring实用程序类或任何其他更好的方法来从PropertySource对象中检索有效的URL / Stream / filepath。

最后的笔记

  • 我无法手动或任何路径查找环境变量。这需要是通用的,并且是从PropertySource对象派生的。

非常感激。