Search code examples
springservletsjavabeansdefaultdispatcher

How does spring Dispatcher Servlet create default beans without any XML configuration?


How does Spring Dispatcher Servlet create Default beans without any predefined XML configuration file. (I am not talking of annotations).

If we don't give any default:

1) Handler mapping object 2) Multipart Resolver 3) Theme Resolver etc... in the XML configuration file, Spring automatically creates these beans.

How does Spring create these beans when there is no explicit declaration of these beans anywhere? And once created are these default beans available in the Application Context? I mean can we get these beans with a call to getBean() method on the context object?


Solution

  • Check out DispatcherServlet.initStrategies():

    protected void initStrategies(ApplicationContext context) {
        initMultipartResolver(context);
        initLocaleResolver(context);
        initThemeResolver(context);
        initHandlerMappings(context);
        initHandlerAdapters(context);
        initHandlerExceptionResolvers(context);
        initRequestToViewNameTranslator(context);
        initViewResolvers(context);
    }
    

    You'll note that DispatcherServlet tries to find existing beans with some fixed name and either uses default or nothing if non found.

    1) Handler mapping object

    No resolver is used if no other resolver is configured.

    2) Multipart Resolver

    Check out AnnotationDrivenBeanDefinitionParser.parse() - quite complex, be warned.

    3) Theme Resolver

    FixedThemeResolver is used if no other resolver is configured.

    The internals of Spring MVC context startup are too complex for a reason - you should not mess around with them. Just supply callbacks or beans you want to replace.