Adding system properties in Spring MVC webapp

2019-07-19 07:36发布

I am using Hibernate 4.3.7.Final and Log4j2 in my Spring MVC webapp, published via Tomcat 7. All configuration is done via JavaConfig (i.e. there is no web.xml or other XML config files).

By default the Hibernate logging does not go through Log4j, for reasons explained in the Apache wiki. In order to resolve this I need to create a system setting as follows:

System.setProperty("org.jboss.logging.provider", "slf4j");

As my application is a webapp there is no Main thread, and as a result I an unsure where to put this System.setProperty call. Any advice would be appreciated.

2条回答
时光不老,我们不散
2楼-- · 2019-07-19 07:51

You could define this system property in context listener which is the first entry point as below:

@WebListener
public class ContextListenerExample implements ServletContextListener {
    public void contextInitialized(ServletContextEvent e){
        System.setProperty("org.jboss.logging.provider", "slf4j");
    }
}

You could even define system property using spring as below:

<bean id="setupJBossLoggingProperty"
    class="org.springframework.batch.support.SystemPropertyInitializer"
       p:keyName="org.jboss.logging.provider" p:defaultValue="slf4j"/>

And then you could say something like:

<bean id="entityManagerFactory"
     class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"
     depends-on="setupJBossLoggingProperty">
 ...

So this means system property will be setted first and then hibernate bean is going to be initialised.

查看更多
叛逆
3楼-- · 2019-07-19 08:00

If you are using some WebApplicationInitializer implementation to bootstrap your Spring application (which I assume you are since you have no web.xml) you could put it in onStartup() method like this:

@Override
public void onStartup(ServletContext servletContext) throws ServletException {
    System.setProperty("org.jboss.logging.provider", "slf4j");
}
查看更多
登录 后发表回答