This is the fifth day of my participation in the November Gwen Challenge. Check out the details: The last Gwen Challenge 2021
The first problem I encountered was that I could not load mybatis-config.xml
Official website how to write how to write, and then reported an error
Well, I’m sure there are files in this path, and neither the relative path nor the absolute path is written to load the global configuration file. After much soul-searching, I decided to find out how people load files instead of using the official website. As a result, the more check more disorderly, the arrangement of the silk.
Either way, the final internal implementation is based on the Class or the ClassLoader’s getResourceAsStream(). Let’s first look at how these two methods are obtained.
My mybatis-config. XML is in the resource path and LoadConfigUtil is my tool class for loading configuration files
// Obtain method 1: InputStream InputStream = by ClassLoader LoadConfigUtil.class.getClassLoader().getResourceAsStream("mybatis-config.xml"); / / access 2: way by class InputStream InputStream = LoadConfigUtil. Class. The getResourceAsStream ("/mybatis - config. XML ");Copy the code
Both methods can be loaded into the mybatis-config. XML configuration file in the resource path, which is written differently.
-
Classloader.getresource (String name) can only match resources from the root of the classpath (resources is the default classpath when Maven builds the project). Writing this. GetResource (” mybatis – config. XML “);
-
Class.getresource (String name) Matches resources from the path of the package in which the current Class is located. You can also get the resource from the classpath root: class.getResource (“/mybatis-config.xml”);
Summary: Select not/when ClassLoader is loaded, Class loading file with/starts from the path of the current Class to match resources.
Tried loading the global configuration file in file folder under the LoadConfigUtil package as follows
/ / access 2: way by class InputStream InputStream = LoadConfigUtil. Class. The getResourceAsStream (" XML file/mybatis - config. ");Copy the code
The log shows that the global configuration file cannot be loaded, and the debug message shows that the loading path is correct. The error message shows that the global configuration file mybatis-config. XML cannot be loaded.
This is the source of the Class load file stream, will find if the current Class is empty will still use the ClassLoader to load
public InputStream getResourceAsStream(String name) {
name = resolveName(name);
ClassLoader cl = getClassLoader0();
if (cl==null) {
// A system class.
return ClassLoader.getSystemResourceAsStream(name);
}
return cl.getResourceAsStream(name);
}
Copy the code