java – 如何在spring的xmls中定义变量以在log4j.properties中使用

这里的一个难题.

我在WAR中有一个应用程序那里有web.xml和application context.xml,还有log4j.properties.此WAR以tomcat运行.

有可能在log4j.properties中使用一些变量,例如log4j.appender.file.File = ${} catalina.base /logs/app.log

我想在web.xml或context.xml中定义一个变量,并在log4j.properties中使用它.例如,以某种方式设置version = 1.1并使用log4j.appender.file.File = ${catalina.base} / logs / app – ${version} .log.它不应该是一个环境变量.

我可以不重新编译应用程序吗?


不应该影响任何东西,只是为了防止…

它的web.xml如下所示:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
          http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
     version="2.5"
     xmlns="http://java.sun.com/xml/ns/javaee">

<!-- Spring -->
<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:context.xml</param-value>
</context-param>

<!-- log4j -->
<listener>
    <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
</listener>
<context-param>
    <param-name>log4jConfigLocation</param-name>
    <param-value>classpath:log4j.properties</param-value>
</context-param>
<context-param>
    <param-name>log4jRefreshInterval</param-name>
    <param-value>10000</param-value>
</context-param>
<context-param>
    <param-name>log4jExposeWebAppRoot</param-name>
    <param-value>false</param-value>
</context-param>
...
</web-app>
创建org.springframework.web.util.Log4jConfigListener的子类,将版本值公开为系统变量(当然,您可以通过标准的System / Java环境变量传递值).

public class TestListener extends Log4jConfigListener{

    @Override
    public void contextInitialized(ServletContextEvent pEvent) {
        String value = pEvent.getServletContext().getInitParameter("version");
        String version = System.getProperty("version");
        if (version == null || version.trim().length()==0) System.setProperty("version", value);

        super.contextInitialized(pEvent);
    }
}

并修复您的web.xml

 <?xml version="1.0" encoding="UTF-8"?>
    <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
              http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
         version="2.5"
         xmlns="http://java.sun.com/xml/ns/javaee">

    <!-- Spring -->
    ...
    <!-- log4j -->
    <listener>
        <listener-class>com.TestListener</listener-class>
    </listener>
    <context-param>
        <param-name>version</param-name>
        <param-value>1.1</param-value>
    </context-param>
    ...
http://stackoverflow.com/questions/31666937/how-to-define-variables-in-springs-xmls-to-use-in-log4j-properties

本站文章除注明转载外,均为本站原创或编译
转载请明显位置注明出处:java – 如何在spring的xmls中定义变量以在log4j.properties中使用