Reputation: 352
Am developing application in spring boot.I have the two packages inside src/main/java 1. com.project.test and 2. wsdl. Inside first package I have spring boot main class. inside second package I have test.wsdl file. I try to load the test.wsdl file in main class using below code
URL wsdl = MainClass.class.getClassLoader().getResource(/wsdl/test.wsdl);
system.out.println("wsdl: "+wsdl);
It return null while run in Eclipse. When build application as jar and run application using java -jar app.jar. It return correct path. Why it return null in Eclipse. But when I run below code without prefix '/' like below. Its working fine in both Eclipse and JAR
URL wsdl = MainClass.class.getClassLoader().getResource(wsdl/test.wsdl);
system.out.println("wsdl: "+wsdl);
But my requirement is to load resource using path /wsdl/test.wsdl
Upvotes: 0
Views: 846
Reputation: 3993
To quote relevant Java documentation (emphasis mine):
Resource Names
A common convention for the name of a resource used by a class is to use the fully qualified name of the package of the class, but convert all periods (
.
) to slashes (/
), and add a resource name of the formname.extension
. To support this, and to simplify handling the details of system classes (for whichgetClassLoader
returnsnull
), the classClass
provides two convenience methods that call the appropriate methods inClassLoader
.The resource name given to a Class method may have an initial starting "/" that identifies it as an "absolute" name. Resource names that do not start with a "/" are "relative".
Absolute names are stripped of their starting "/" and are passed, without any further modification, to the appropriate ClassLoader method to locate the resource. Relative names are modified according to the convention described previously and then are passed to a ClassLoader method.
Link: Accessing Resources
Upvotes: 1
Reputation: 13103
You need to move wsdl/test.wsdl
inside src/main/resources
in order to load resource.
When you package you app.jar
, wsdl/test.wsdl
goes into root path inside jar file, so .getClassLoader().getResource("wsdl/test.wsdl")
works as expected.
Upvotes: 1