monksy
monksy

Reputation: 14234

Dependency of war looks for a file in the classpath

I am using a shared library as a dependency to my Java EE project. The War file is being deployed to Tomcat.

The shared library relies on a file being found within the classpath. Is there a way to guarentee that the file will be within the classpath? I am not able to hard code the path of the file within the shared library. Nor can I avoid using the classes that require it.

Upvotes: 1

Views: 6520

Answers (3)

alexkasko
alexkasko

Reputation: 4925

If shared library (e.g. lib1) is yours - then you can pack necessary files into it's jar. Root folder of the jar is root of classpath.

If lib1 is third-party, you can create lib1-res library with this file in jar. And always use this libraries together (make lib1-res dependent on lib1 in case of maven used).

Upvotes: 1

Brad
Brad

Reputation: 15879

Packaging your WAR

The simplest solution is to package all dependant JAR files and classes inside your deployable WAR file if you can. Then you have control over how they are loaded from your designated classpath.

As BGR mentioned all your compiled java scource (*.class files) should be available in your WAR file under the web-inf\classes directory

Any supporting JAR files should be place under the web-inf\lib directory inside your WAR file.

Tomcat knows about these directory structures as it is an industry standard format for WAR files.

You can of course deviate from this standard structure and load JAR files from elsewhere outside of your WAR, but then you have to understand potential class loading issues. What I have mentioned is the simplest way forward.

Does a file exist on the classpath?

In your application you can do something like this to check to see if a specific file exists on your classpath.

URL resource = this.getClass().getClassLoader().getResource(path);

Here's some additional reading from Oracle about Location-Independent Access to Resources

Upvotes: 2

Bruno Grieder
Bruno Grieder

Reputation: 29834

Anything in WEB-INF/classes in your war is in the 'classpath' (assuming it is seeked by a class loaded using the URLClassLoader of your webapp).

Can you have your file copied there during packaging?

Upvotes: 0

Related Questions