我希望在我的@PropertySource注释中的路径中包含一个'/‘或'\’,这样它就可以在Linux或Windows下运行。
我试过了
@PropertySource("${dir} + #{T(File).separator} + "${name}")和一些变化,但没有运气。
如何在我的@PropertySource中包含与平台无关的文件路径分隔符?
发布于 2018-05-08 02:36:06
您说得对,这个问题如何适用于很多人(即开发Windows环境与prod Unix环境,等等)是很奇怪的。
一个自然的答案是,您只需将正确的“斜杠”放在实际dir属性的末尾,格式与OS特定的文件路径类型相同。否则..。
这里有一个解决方案,假设您获得了OS环境中的${dir}本地文件系统格式和name文件路径,您可以这样做:
@PropertySource(name = "theFileInDir.properties",value = { "file:${dir}" }, factory = OSAgnosticPropertySourceFactory.class) 然后,为@PropertySource#factory注释元素创建一个@PropertySource#factory,如下所示:
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、value和factory元素)来使用Java7 Path解析与操作系统无关的文件位置。
您可以使用PropertySourceFactory做更多的事情,但我认为这对您来说已经足够了。我希望看到其他的答案,我自己也遇到过这个问题,所以我很高兴你能让我想到解决这个问题的方法!
https://stackoverflow.com/questions/50223158
复制相似问题