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

时间:2018-06-04 07:11:14

标签: 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.

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

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

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

PropertySource对象有一个getName()方法,它看起来包含我需要的信息,但不是友好的。

具有类路径的PropertySource上的

getName显示: -

class path resource [internal.properties]
具有文件路径的PropertySource上的

getName显示: -

URL [file:C:/Dev/conf/application.properties]

括号内的信息几乎可用。文件1是有效的URL,类路径不是。

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

最后的笔记

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

非常感谢。

0 个答案:

没有答案