简体   繁体   English

Spring 4 WebApplicationInitializer log4j2多个初始化问题

[英]Spring 4 WebApplicationInitializer log4j2 multiple initialization issues

I am building an application using 100% code configuration approach for a spring 4 web app. 我正在为Spring 4 Web应用程序使用100%代码配置方法构建应用程序。 Following is my web config class. 以下是我的Web配置类。

public class WebAppInitializer extends Log4jServletContainerInitializer implements WebApplicationInitializer {


    public void onStartup(ServletContext container) throws ServletException {
        super.onStartup(null, container);

        // Create the 'root' Spring application context
        AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();
        rootContext.register(MyAppContext.class);

        // Manage the lifecycle of the root application context
        container.addListener(new ContextLoaderListener(rootContext));

        // Create the dispatcher servlet's Spring application context
        AnnotationConfigWebApplicationContext webContext = new AnnotationConfigWebApplicationContext();
        webContext.register(MyServletContext.class);

        // Register and map the dispatcher servlet
        ServletRegistration.Dynamic dynamic = container.addServlet("dispatcher", new DispatcherServlet(webContext));
        dynamic.setLoadOnStartup(1);
        dynamic.addMapping("/api/*");
    }
}

Problem - 问题-

a. 一种。 My spring beans are getting initialized twice 我的四季豆初始化了两次

b. b。 Whenever I add logj2.xml in my resources (using maven), then my bean creation fails. 每当我在我的资源中添加logj2.xml(使用Maven)时,我的bean创建都会失败。

I am new to this, kindly help me. 我是新来的,请帮助我。

Log4J - 2.5, Tomcat - 8.0.32 Log4J-2.5,Tomcat-8.0.32

Thanks! 谢谢!

I managed to fix it. 我设法解决了。 It was not the problem with WebApplInitializer but with Spring Java Configurations files. 这不是WebApplInitializer的问题,而是Spring Java Configurations文件的问题。 I was maintaining separate configs for ApplicationContext and ServletContext. 我正在为ApplicationContext和ServletContext维护单独的配置。 In ApplicationContext, using 在ApplicationContext中,使用

@ComponentScan(value = "com.application.module", 
excludeFilters = {@ComponentScan.Filter(value = {Configuration.class})})

did the trick. 做到了。

In servlet context, I used - 在servlet上下文中,我使用-

@ComponentScan(basePackageClasses = AppContext.class)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM