Search This Blog

Monday, May 5, 2014

How to initialize and configure Spring MVC application without creating any *-servlet.xml?

Spring Annotations From its beginning, Spring’s most common means of configuration has been XML-based. But as developers grow weary of navigating through a seemingly endless maze of angle-brackets, some have started looking for other ways to wire the beans in their Spring-enabled applications. Spring has responded with several annotation-driven configuration options. In this post, you will find a guide to all of the annotations supported in Spring 2.5.

To configure your application by using annotations we need to override 'onStartup' method of 'WebApplicationInitializer' Interface.

To get more detail about this please refer the following code snippet-



 WebApplicationContext context = getContext();
        servletContext.addListener(new ContextLoaderListener(context));
//Register your dispatcher servlet into servlet context
        ServletRegistration.Dynamic dispatcher = servletContext.addServlet(ApplicationConstants.SERVLET_NAME, new DispatcherServlet(context));
        dispatcher.setLoadOnStartup(1);
//provide your default or base path mapping here
        dispatcher.addMapping(ApplicationConstants.BASE_PATH);

Remember getContext() is a custom method to get Context of your application ,This would be implemented like -

 AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
        context.setConfigLocation(ApplicationConstants.CONFIG_LOCATION);

        return context;
Where config location is your component classes location path.

Hope you like this tutorial, Please keep questioning and comment on this.


1 comment :