简体   繁体   中英

File.separator in @PropertySource

I would like to include a '/' or a '\\' in the path in my @PropertySource annotation, so that it will run under either Linux or Windows.

I have tried

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

and a number of variations, but with no luck.

How can I include a platform-independent file path separator character in my @PropertySource ?

You're right, it's weird how this issue can apply to a lot of people (ie dev Windows environment vs. prod Unix environment, etc.).

One natural answer would be that you just put the right trailing "slash" on the end of the actual dir property in the same format as the OS specific filepath type. Otherwise...

Here's a solution, assuming you're given ${dir} in the OS environment native file system format and a name file path in, you could do:

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

Then, you'd create a PropertySourceFactory for the @PropertySource#factory annotation element like so:

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));
    }

}

I like my solution because you can leverage the basic elements (eg name , value , and factory elements) all in the @PropertySource annotation itself to resolve an OS-agnostic file location with Java 7 Path .

You can do more with the PropertySourceFactory , but I think this should suffice for you. I'd love to see other answers on this; I've encountered this issue myself, so I'm glad you got me thinking about a way to go about solving this!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM