QueryLoader类,是一个从一个文件加载查询到一个Map的简单的类。然后,当需要的时候,你从Map中选择一些查询。当然了,这个方法的实现是比较简单的。现看看文件载入的源代码:
- /**
- * 载入一个查询命名和SQL值映射的Map集合.
- * 此Map被缓存以便以后相同路径的请求可以返回被缓存的Map
- * Loads a Map of query names to SQL values. The Maps are cached so a
- * subsequent request to load queries from the same path will return
- * the cached Map.
- *
- * @param path The path that the ClassLoader will use to find the file.
- * ClassLoader通过path查找文件
- *
- * This is <strong>not</strong> a file system path. If you had a jarred
- * Queries.properties file in the com.yourcorp.app.jdbc package you would
- * pass "/com/yourcorp/app/jdbc/Queries.properties" to this method.
- * 这不是一个文件系统路径。如果你有一个Queries.properties文件在com.yourcorp.app.jdbc这个包下,
- * 那么你应该传递"/com/yourcorp/app/jdbc/Queries.properties"参数到这个方法.
- *
- * @throws IOException if a file access error occurs
- * @throws IllegalArgumentException if the ClassLoader can't find a file at
- * the given path.
- * @return Map of query names to SQL values
- */
- public synchronized Map<String,String> load(String path) throws IOException {
- Map<String,String> queryMap = (Map<String,String>) this.queries.get(path);
- if (queryMap == null) {
- queryMap = this.loadQueries(path);
- this.queries.put(path, queryMap);
- }
- return queryMap;
- }
这个方法加入了同步锁机制,所以是线程安全的,这个方法需要注意的一点就是传入的路径,因为是通过ClassLoader载入,所以,传入的路径是绝对路径名。首先呢,先从本地的Map集合queries拿到路径名里对应的集合,如果为空,则说明没有缓存对不对,OK,没有就加呗,来loadQueries方法:
- /**
- * Loads a set of named queries into a Map object. This implementation
- * reads a properties file at the given path.
- *
- * 加载命名查询集到一个Map对象中.
- * 这个实现用于读取给定路径的Properties文件
- *
- * @param path The path that the ClassLoader will use to find the file.
- * ClassLoader使用指定的path去查找file
- * @throws IOException file访问异常
- * @throws IllegalArgumentException ClassLoader查找不到指定路径的文件
- * @since DbUtils 1.1
- * @return Map of query names to SQL values 查询名称到SQL值的映射集合
- */
- @SuppressWarnings("unchecked")
- protected Map<String,String> loadQueries(String path) throws IOException {
- // Findbugs flags getClass().getResource as a bad practice; maybe we should change the API?
- InputStream in = getClass().getResourceAsStream(path);//获取指定文件的流对象
- if (in == null) {
- throw new IllegalArgumentException(path + " not found.");
- }
- Properties props = new Properties();
- props.load(in);
- // Copy to HashMap for better performance
- return new HashMap(props);
- }
哝,有没有?!通过ClassLoader载入指定文件流对象,如果为空,则会抛出找不到文件的异常。否则呢,载入Properties文件并以HashMap返回。
载入了未缓存的properties文件,那么,存一个:
- this.queries.put(path, queryMap);
完成了载入、缓存,缓存这个东西呢是要占内存的,所以呢,不要缓存太多或者大的对象,除非有必要,建议各位用完就remove掉:
- /**
- * Removes the queries for the given path from the cache.
- * 从缓存中删除指定的路径
- * @param path The path that the queries were loaded from.
- * queries载入的路径
- */
- public synchronized void unload(String path){
- this.queries.remove(path);
- }