@PropertySource中的文件分隔符



我想在我的@PropertySource注释的路径中包含"/"或"\",以便它可以在Linux或Windows下运行。

我试过了

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

和一些变化,但没有运气。

如何在@PropertySource中包含独立于平台的文件路径分隔符?

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

一个自然的答案是,您只需将正确的尾随"斜杠"放在实际dir属性的末尾,格式与操作系统特定的文件路径类型相同。否则。。。

这是一个解决方案,假设您以操作系统环境本机文件系统格式获得${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));
}
}

我喜欢我的解决方案,因为您可以利用基本元素(例如namevaluefactory元素(全部在@PropertySource注解本身中,以使用 Java 7Path解析与操作系统无关的文件位置。

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

最新更新