log4j自动加载配置文件
org.apache.log4j.LogManager类有一个静态块,首先是找log4j.xml,找不到的情况下才找log4j.properties
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
// if the user has not specified the log4j.configuration // property, we search first for the file "log4j.xml" and then // "log4j.properties" if (configurationOptionStr == null ) { url = Loader.getResource(DEFAULT_XML_CONFIGURATION_FILE); if (url == null ) { url = Loader.getResource(DEFAULT_CONFIGURATION_FILE); } } else { try { url = new URL(configurationOptionStr); } catch (MalformedURLException ex) { // so, resource is not a URL: // attempt to get the resource from the class path url = Loader.getResource(configurationOptionStr); } } |
2,然后是怎么找呢:如下代码,是委托给classloader(加载Loader类的classloader)去找了,
1
2
3
4
5
6
7
8
9
10
11
|
// We could not find resource. Ler us now try with the // classloader that loaded this class. classLoader = Loader. class .getClassLoader(); if (classLoader != null ) { LogLog.debug( "Trying to find [" +resource+ "] using " +classLoader + " class loader." ); url = classLoader.getResource(resource); if (url != null ) { return url; } } |
3,classloader的getResource(...)又是怎么找呢:总是先从父classloader里去找,找不到才自己去找
1
2
3
4
5
6
7
8
9
10
11
12
|
public URL getResource(String name) { URL url; if (parent != null ) { url = parent.getResource(name); } else { url = getBootstrapResource(name); } if (url == null ) { url = findResource(name); } return url; } |
感谢您的阅读,您的支持是我写博客动力。