ClassPathResource
What is ClassPath
ClassPath is the path where the class files are searched. In containers such as Tomcat, ClassPath usually points to WEB-INF/classes
. In ordinary Java programs, we can define the path where class files are searched by specifying the -cp
or -classpath
parameters. These paths are ClassPath.
For the convenience of the project, the configuration files we define cannot use absolute paths, so relative paths are used. The best way in this case is to put the configuration files together with the class files for easy search.
Origin
In the process of Java coding, we often hope to read configuration files within the project. According to the habits of Maven, these files are usually placed under the src/main/resources
of the project. When reading, use:
String path = "config.properties";
InputStream in = this.class.getResource(path).openStream();
Using the current class to obtain resources actually means obtaining resources using the class loader of the current class, and finally obtaining an input stream to read the file stream using the openStream()
method.
Encapsulation
To simplify the reading of resources in ClassPath, we encapsulated the ClassPathResource
class:
ClassPathResource resource = new ClassPathResource("test.properties");
Properties properties = new Properties();
properties.load(resource.getStream());
Console.log("Properties: {}", properties);
This greatly simplifies the reading of resources in ClassPath.
Hutool provides encapsulation classes
Props
for properties and more powerful configuration file Setting class. These two classes have encapsulated ClassPath, allowing you to read configuration files in a more convenient way. Please refer to theHutool-setting
chapter for related documentation.