2016-03-22 16 views
0

我正在爲Spring 4 Web應用程序使用100%代碼配置方法構建應用程序。以下是我的網絡配置類。Spring 4 WebApplicationInitializer log4j2多個初始化問題

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/*"); 
    } 
} 

問題 -

一個。我的春豆兩次得到初始化

b。每當我在資源中添加logj2.xml(使用maven)時,我的bean創建失敗。

我是新來的,請幫助我。

Log4J-2.5,Tomcat-8.0.32

謝謝!

回答

0

我設法解決它。這不是WebApplInitializer的問題,而是Spring Java配置文件。我爲ApplicationContext和ServletContext維護了不同的配置。在ApplicationContext中,使用

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

訣竅。

在servlet上下文,我用 -

@ComponentScan(basePackageClasses = AppContext.class)