web.xml加载顺序2

启动容器时,listener的加载必定在 filter 和 servlet 之前,与listener在web.xml中的位置无关,

但是,对于不同的listener来说, 写在前面的listener肯定是要先加载的, 因此listener之间一些顺序问题 还是应该注意的,

比如:

加载ServletContextListener 和  Log4jConfigListener , 如果ServletContext监听中要输出日志,那么 Log4jConfigListener 肯定要先被加载,也就是说Log4jConfigListener的<listener>必须配置在ServletContextListener之前

工程结构:

 监听类:

package com.chaol.listener;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import org.apache.log4j.Logger;

public class BaseContextListener implements ServletContextListener {
	private static Logger logger = Logger.getLogger(BaseContextListener.class);

	@Override
	public void contextDestroyed(ServletContextEvent arg0) {
		
	}

	@Override
	public void contextInitialized(ServletContextEvent arg0) {
		ServletContext context = arg0.getServletContext();
		String logPropertiesPath = context.getInitParameter("log4j");
		logger.info("启动容器,创建监听");
		System.out.println(logPropertiesPath);
	}
}

web.xml 配置1(错误的配置) :

<context-param>
	<param-name>log4jConfigLocation</param-name>
	<param-value>/WEB-INF/log4j.properties</param-value>
</context-param>
<context-param>
	<description>path of the logs</description>
	<param-name>log4j</param-name>
	<param-value>/WEB-INFO/logs</param-value>
</context-param>

<listener>
	<listener-class>com.chaol.listener.BaseContextListener</listener-class>
</listener>

<listener>
	<listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
</listener>

上面代码中BaseContextListener监听配置在Log4jConfigListener监听之前,报错信息如下,在还没有加载log4j 日志对象之前就使用了日志打印,很明显会出错

web.xml配置2(正确的配置) :

<context-param>
	<param-name>log4jConfigLocation</param-name>
	<param-value>/WEB-INF/log4j.properties</param-value>
</context-param>
<context-param>
	<description>path of the logs</description>
	<param-name>log4j</param-name>
	<param-value>/WEB-INFO/logs</param-value>
</context-param>

<listener>
	<listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
</listener>

<listener>
	<listener-class>com.chaol.listener.BaseContextListener</listener-class>
</listener>

容器启动结果,明显日志对象生效了,在控制台打印出了日志信息:

下面贴出我的log4j.properties配置:

log4j.rootLogger=DEBUG,stdout,rollingFile

# 控制台输出
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout.ConversionPattern=[%d] [%t] [%5p] [%c.%M(%F:%L)] - %m%n

# 文件输出
log4j.appender.rollingFile=org.apache.log4j.DailyRollingFileAppender
log4j.appender.rollingFile.Append=true
##log4j.appender.rollingFile.File=d:/logs/log1.log
log4j.appender.rollingFile.layout=org.apache.log4j.PatternLayout
log4j.appender.rollingFile.layout.ConversionPattern=[%d] [%t] [%5p] [%c.%M(%F:%L)] - %m%n

猜你喜欢

转载自blog.csdn.net/ex_tang/article/details/82560524