Spring Boot Source - Yash-777/MyWorld GitHub Wiki

DispatcherServlet 3.0.0.M3, 3.0.0.M4

<web-app>
    <servlet>
        <servlet-name>example</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>example</servlet-name>
        <url-pattern>*.form</url-pattern>
    </servlet-mapping>
</web-app>

image

public class DispatcherServlet extends FrameworkServlet {}

Auto-configuration for the Spring DispatcherServlet. Should work for a standalone application where an embedded web server is already present and also for a deployable application using SpringBootServletInitializer.

SpringBootServletInitializer – Deploy WAR file to Tomcat inkedin.com post


SpringApplication.run( MyApp.class ) internally where it initializes dispatcher servlet. proof from source code SpringBoot 2.7.1 version

Sure, here's the proof from the Spring Boot 2.7.1 source code:

The SpringApplication.run() method initializes the DispatcherServlet through the WebApplicationInitializer mechanism. Specifically, the run() method first creates an instance of SpringApplication and then calls its run() method, passing in the MyApp.class argument:

public static void main(String[] args) {
    SpringApplication.run(MyApp.class, args);
}

The SpringApplication.run() method then performs a number of initialization steps, including initializing the WebApplicationInitializer instances:

public ConfigurableApplicationContext run(String... args) {
    // ...
    prepareContext(context, environment, listeners, applicationArguments, printedBanner);
    refreshContext(context);
    afterRefresh(context, applicationArguments);
    // ...
}

private void prepareContext(ConfigurableApplicationContext context, 
                            ConfigurableEnvironment environment,
                            List<ApplicationListener<?>> listeners, 
                            SpringApplicationRunArguments args, 
                            Banner printedBanner) {
    // ...
    WebApplicationType webApplicationType = deduceWebApplicationType();
    if (!webApplicationType.equals(WebApplicationType.NONE)) {
        // ... create and configure the web environment ...
        context.setEnvironment(environment);
        configureListeners(listeners);
        context.addApplicationListener(new SourceFilteringListener(context, new SkipFailedStartupInfoLogger()));
        // ...
        ServletWebServerFactory serverFactory = getWebServerFactory(context);
        if (serverFactory != null) {
            customizeWebServerFactory(serverFactory);
            context.getBeanFactory().registerSingleton("webServerFactory", serverFactory);
        }
        // ...
        for (WebApplicationInitializer initializer : getWebApplicationInitializers(context)) {
            initializer.onStartup(servletContext);
        }
        // ...
    }
    // ...
}

private List<WebApplicationInitializer> getWebApplicationInitializers(ConfigurableApplicationContext context) {
    List<WebApplicationInitializer> initializers = new ArrayList<>();
    // ...
    initializers.addAll(context.getBeansOfType(WebApplicationInitializer.class).values());
    // ...
    AnnotationAwareOrderComparator.sort(initializers);
    return initializers;
}

The prepareContext() method deduces the type of web application (i.e., whether it's a servlet-based web application or not) and if it is, it configures the ServletContext and initializes the WebApplicationInitializer instances. The getWebApplicationInitializers() method retrieves all beans of type WebApplicationInitializer and adds them to the list of initializers to be executed.

So, the DispatcherServlet is initialized by one of the WebApplicationInitializer instances returned by getWebApplicationInitializers(), which is executed during the prepareContext() method.


@SpringBootApplication
public class MyBootApplication {

    public static void main(String[] args) {
        ApplicationContext ctx = 
                SpringApplication.run( MyBootApplication.class, args );
        
        String[] beanNames = ctx.getBeanDefinitionNames();
        Arrays.sort(beanNames);
        for (String beanName : beanNames) {
            System.out.println(beanName);
        }
    }

}

output: https://howtodoinjava.com/spring-boot2/springbootapplication-auto-configuration/

[ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean  : Servlet dispatcherServlet mapped to [/]
dispatcherServlet
dispatcherServletRegistration
org.springframework.boot.autoconfigure.web.servlet.DispatcherServletAutoConfiguration
org.springframework.boot.autoconfigure.web.servlet.DispatcherServletAutoConfiguration$DispatcherServletConfiguration
org.springframework.boot.autoconfigure.web.servlet.DispatcherServletAutoConfiguration$DispatcherServletRegistrationConfiguration


Common for Annotations: @Retention(RetentionPolicy.RUNTIME) @Documented

package org.springframework.boot.autoconfigure;
@Target(ElementType.TYPE)
@Inherited
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan(excludeFilters = { @Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class),
		@Filter(type = FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class) })
public @interface SpringBootApplication { }  // @since 1.2.0

package org.springframework.boot;
@Target(ElementType.TYPE)
@Configuration
@Indexed
public @interface SpringBootConfiguration {  } // @since 1.4.0
	/*
	Indicates that a class declares one or more @Bean methods andmay be processed by the Spring container to generate bean 
        definitions and service requests for those beans at runtime
	*/
	package org.springframework.context.annotation;
	@Target(ElementType.TYPE)
	@Component
	public @interface Configuration {  }  // @since 3.0

/*
Enable auto-configuration of the Spring Application Context, attempting to guess and configure beans that you are likely to need.
Auto-configuration classes are usually applied based on your classpath and what beans you have defined. For example, if you have 
tomcat-embedded.jar on your classpath you are likely to want a TomcatServletWebServerFactory 
(unless you have defined your own ServletWebServerFactory bean). 
*/
package org.springframework.boot.autoconfigure;
@Target(ElementType.TYPE)
@Inherited
@AutoConfigurationPackage
@Import(AutoConfigurationImportSelector.class)
public @interface EnableAutoConfiguration {  } // @since 1.0.0


@Target(ElementType.TYPE)
@Repeatable(ComponentScans.class)
public @interface ComponentScan { }  // @since 3.1

@ComponentScan : This annotation provides support parallel with Spring XML’s context:component-scan element. baeldung.com

<beans xmlns:context="http://www.springframework.org/schema/context" >
  <context:component-scan base-package="com.github.yash777"/>
  <context:annotation-config/> <!-- the annotation-config tag enables annotation-based mappings -->

  <bean id="accountRepository" class="com.baeldung.applicationcontext.AccountRepository" />
</beans>

Spring will automatically initialize the class which is annotated with @Component and register with the spring container


package org.springframework.web.bind.annotation;
/*
A convenience annotation that is itself annotated with @Controller and @ResponseBody. 

Types that carry this annotation are treated as controllers where @RequestMapping methods assume @ResponseBody semantics by default. 
*/
@Target(ElementType.TYPE)
@Controller   @ResponseBody
public @interface RestController { } // @since 4.0

//@GetMapping is a composed annotation thatacts as a shortcut for @RequestMapping(method = RequestMethod.GET).
@Target(ElementType.METHOD)
@RequestMapping(method = RequestMethod.GET)
public @interface GetMapping {  } // @since 4.3

@Target({ElementType.TYPE, ElementType.METHOD})
@Mapping
public @interface RequestMapping { } // @since 2.5
package org.springframework.stereotype;

/*
 * @see org.springframework.context.annotation.ClassPathBeanDefinitionScanner
*/
@Target(ElementType.TYPE)
@Indexed
public @interface Component {  }  // @since 2.5


/*
 * @see org.springframework.web.bind.annotation.RequestMapping
 * @see org.springframework.context.annotation.ClassPathBeanDefinitionScanner
*/
@Target(ElementType.TYPE)
@Component
public @interface Controller { } // @since 2.5  (e.g. a web controller)

@Target(ElementType.TYPE)
@Component
public @interface Service { }  // @since 2.5   "Business Service Facade"

/*
As of Spring 2.5, this annotation also serves as a specialization of @Component, allowing for implementation classes 
to be autodetected through classpath scanning.

 * @see org.springframework.dao.DataAccessException
 * @see org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor
*/
@Target(ElementType.TYPE)
@Component
public @interface Repository {  }  // @since 2.0  Java EE patterns such as "Data Access Object"
⚠️ **GitHub.com Fallback** ⚠️