How to avoid resource collisions in library jars?

折月煮酒 提交于 2019-12-05 13:01:23

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>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!