@PropertySource中的File.separator

时间:2018-05-07 22:09:01

标签: java spring spring-boot

我想加入' /'或者是' \在@PropertySource注释的路径中,以便它可以在Linux或Windows下运行。

我试过了

@PropertySource("${dir} + #{T(File).separator} + "${name}")

和许多变化,但没有运气。

如何在@PropertySource中包含与平台无关的文件路径分隔符?

1 个答案:

答案 0 :(得分:1)

你是对的,这个问题如何适用于很多人(即开发Windows环境与prod Unix环境等)是很奇怪的。

一个自然的答案就是你只是把正确的尾随"斜线"在实际的dir属性的末尾,其格式与OS特定的文件路径类型相同。否则...

这是一个解决方案,假设您在操作系统环境中使用${dir}本机文件系统格式并且有一个name文件路径,您可以这样做:

@PropertySource(name = "theFileInDir.properties",value = { "file:${dir}" }, factory = OSAgnosticPropertySourceFactory.class) 

然后,您为@PropertySource#factory注释元素创建PropertySourceFactory,如下所示:

public class OSAgnosticPropertySourceFactory implements PropertySourceFactory {

    @Override
    public PropertySource<?> createPropertySource(String name, EncodedResource resource) throws IOException {
        Path resolvedFilePath = Paths.get(resource.getResource().getURI()).resolve(name);
        EncodedResource er = new EncodedResource(new PathResource(resolvedFilePath), resource.getCharset());
        return (name != null ? new ResourcePropertySource(name, er) : new ResourcePropertySource(er));
    }

}

我喜欢我的解决方案,因为您可以利用name注释本身中的基本元素(例如valuefactory@PropertySource元素)来解析操作系统与Java 7 Path相关的文件位置。

您可以使用PropertySourceFactory做更多事情,但我认为这对您来说已经足够了。我很乐意看到其他答案;我自己也遇到过这个问题,所以我很高兴你让我想办法解决这个问题!

相关问题