How to avoid resource collisions in library jars?
And what do you do in Java to avoid collisions between libraries? Packages! This is established and well understood approach. Packages work with resources as well:
com/example/foo/Foo.class
com/example/foo/properties.txt
and second library:
com/example/bar/Bar.class
com/example/bar/properties.txt
Note that properties.txt
lies in different packages and thus directories in final JAR. Actually this approach is preferred because the API for retrieving such resources becomes easier:
App.class.getResourceAsStream("properties.txt"))
vs.
Bar.class.getResourceAsStream("properties.txt"))
It just works because Class.getResourceAsStream()
is by default local to package of underlying class. Of course when you are inside an instance method of either Foo
or Bar
you simply say getClass().getResourceAsStream("properties.txt")
. Moreover you can still reference both files easily, just like you reference classes:
getClass().getResourceAsStream("/com/example/foo/properties.txt");
getClass().getResourceAsStream("/com/example/bar/properties.txt");
I'm skeptical because I haven't seen any Maven example that actually does this.
Real world example: you have a Spring integration test named com.example.foo.FooTest
. By default Spring expects the context file to reside under: /src/test/resources/com/example/foo/FooTest-context.xml
.
To complete the @Tomasz's answer with the maven code to do that :
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
<targetPath>com/example/bar/</targetPath>
</resource>
</resources>
</build>