I am building an application using 100% code configuration approach for a spring 4 web app. Following is my web config class.
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. Whenever I add logj2.xml in my resources (using maven), then my bean creation fails.
I am new to this, kindly help me.
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. I was maintaining separate configs for ApplicationContext and ServletContext. In ApplicationContext, using
@ComponentScan(value = "com.application.module",
excludeFilters = {@ComponentScan.Filter(value = {Configuration.class})})
did the trick.
In servlet context, I used -
@ComponentScan(basePackageClasses = AppContext.class)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.