Sumit Trehan
Sumit Trehan

Reputation: 4045

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?

Upvotes: 1

Views: 1364

Answers (2)

NatFar
NatFar

Reputation: 2220

The default objects are added to the context when the mentioned "init" methods are called. For example, in private void initHandlerMappings(ApplicationContext context), the default handler mappings are obtained by calling getDefaultStrategies(context, HandlerMapping.class). Here, the following happens:

  1. A String[] is populated with the default classnames using the DispatcherServlet.properties

  2. Create a Class instance of each.

  3. But to actually instantiate the default object, it calls the following method, passing in the class instance:

     protected Object createDefaultStrategy(ApplicationContext context, Class<?> clazz) {
         return context.getAutowireCapableBeanFactory().createBean(clazz);
    

    }

It is here that the default objects are fully initialized as beans.

Upvotes: 0

Tomasz Nurkiewicz
Tomasz Nurkiewicz

Reputation: 340923

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.

Upvotes: 1

Related Questions