How to use properties in a Spring project to confi

2019-06-18 12:55发布

I have multiple properties files in my Spring project. The spring context loads these properties and handles property overriding in a convenient manner. Is there a way to take the properties that are available to my Spring configuration XML files (ie. ${myprop}) and use them in a similar fashion in my log4j.xml file? I know that I can pass system properties to log4j using -Dprop=value on startup, but I would prefer having all of the configuration in the properties files in my project. Is this possible?

My app runs in Tomcat.

2条回答
闹够了就滚
2楼-- · 2019-06-18 13:41

Try to use this class, after integrating your multiple properties files to one Properties.

public class DOMConfiguratorWithProperties extends DOMConfigurator {

    private Properties propertiesField = null;

    public synchronized Properties getProperties() {
        return propertiesField;
    }

    public synchronized void setProperties(final Properties properties) {
        propertiesField = properties;
    }

    @Override
    protected String subst(final String value) {
        return super.subst(value, getProperties());
    }

    public static void configure(final String filename) {
        new DOMConfiguratorWithProperties().doConfigure(
                filename,
                LogManager.getLoggerRepository());
    }

    public static void configure(
            final String filename,
            final Properties properties) {
        DOMConfiguratorWithProperties configurator = new DOMConfiguratorWithProperties();
        configurator.setProperties(properties);
        configurator.doConfigure(
                filename,
                LogManager.getLoggerRepository());
    }
}
查看更多
再贱就再见
3楼-- · 2019-06-18 13:41

I think the only way you can interact with Log4J is through the Nested diagnostic context.

So if you are very desperate, you could write a Spring AOP aspect that sets the diagnostic context for your Spring Bean logs (and you could use the properties there). However, that would require that the Log be available to the Spring Bean, so you would need to add a getLog() method to your service interfaces (this gets a lot easier if you use static AspectJ compilation and is described in AspectJ in Action).

But short of using AOP, I can't think of a sensible way to let Spring and Log4J interact.

查看更多
登录 后发表回答