title: Why does Spring throw "IllegalStateException: No ServletContext set" when using a WebApplicationInitializer
body: <p>im just learning java, and now try to creat UI for my application with using MVC+thymeleaf. When i try to run application, i get error, stacktrace like this:</p>
  
  <pre><code> Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'resourceHandlerMapping' defined in org.springframework.web.servlet.config.annotation.DelegatingWebMvcConfiguration: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.web.servlet.HandlerMapping]: Factory method 'resourceHandlerMapping' threw exception; nested exception is java.lang.IllegalStateException: No ServletContext set
      at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:656)
      at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:636)
      at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1338)
      at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1177)
      at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:557)
      at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:517)
      at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:323)
      at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
      at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:321)
      at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202)
      at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:882)
      at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:878)
      at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:550)
      at org.springframework.context.annotation.AnnotationConfigApplicationContext.&lt;init&gt;(AnnotationConfigApplicationContext.java:89)
      at com.foxminded.university.Main.main(Main.java:26)
  Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.web.servlet.HandlerMapping]: Factory method 'resourceHandlerMapping' threw exception; nested exception is java.lang.IllegalStateException: No ServletContext set
      at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:185)
      at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:651)
      ... 14 more
  Caused by: java.lang.IllegalStateException: No ServletContext set
      at org.springframework.util.Assert.state(Assert.java:73)
      at org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport.resourceHandlerMapping(WebMvcConfigurationSupport.java:534)
      at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
      at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
      at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
      at java.base/java.lang.reflect.Method.invoke(Method.java:567)
      at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:154)
      ... 15 more
  </code></pre>
  
  <p>my config file:</p>
  
  <pre><code>@Configuration
  @ComponentScan("com.foxminded.university")
  @PropertySource("classpath:config.properties")
  @EnableWebMvc
  public class ContextConfig implements WebMvcConfigurer {
  
      private final ApplicationContext applicationContext;
  
      @Value("${url}")
      public String url;
      @Value("${user}")
      public String user;
      @Value("${password}")
      public String password;
      @Value("${driverClass}")
      public Class&lt;Driver&gt; driverClass;
  
      @Autowired
      public ContextConfig(ApplicationContext applicationContext) {
          this.applicationContext = applicationContext;
      }
  
      @Bean
      public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
          return new PropertySourcesPlaceholderConfigurer();
      }
  
      @Bean
      public JdbcTemplate jdbcTemplate(DataSource dataSource) {
          return new JdbcTemplate(dataSource);
      }
  
      @Bean
      public DataSource dataSource() {
          SimpleDriverDataSource dataSource = new SimpleDriverDataSource();
          dataSource.setDriverClass(driverClass);
          dataSource.setUsername(user);
          dataSource.setUrl(url);
          dataSource.setPassword(password);
          return dataSource;
      }
  
      @Bean
      public SpringResourceTemplateResolver templateResolver() {
          SpringResourceTemplateResolver templateResolver = new SpringResourceTemplateResolver();
          templateResolver.setApplicationContext(applicationContext);
          templateResolver.setPrefix("/WEB-INF/views/");
          templateResolver.setSuffix(".html");
          templateResolver.setTemplateMode(TemplateMode.HTML);
          return templateResolver;
      }
  
      @Bean
      public SpringTemplateEngine templateEngine() {
          SpringTemplateEngine templateEngine = new SpringTemplateEngine();
          templateEngine.setTemplateResolver(templateResolver());
          templateEngine.setEnableSpringELCompiler(true);
          return templateEngine;
      }
  
      @Override
      public void configureViewResolvers(ViewResolverRegistry registry) {
          ThymeleafViewResolver resolver = new ThymeleafViewResolver();
          resolver.setTemplateEngine(templateEngine());
          registry.viewResolver(resolver);
      }
  }
  </code></pre>
  
  <p>dispatcherServlet:</p>
  
  <pre><code>public class SpringMvcDispatcherServletInitializer extends AbstractAnnotationConfigDispatcherServletInitializer{
  
      @Override
      protected Class&lt;?&gt;[] getRootConfigClasses() {
          return null;
      }
  
      @Override
      protected Class&lt;?&gt;[] getServletConfigClasses() {    
          return new Class[] {ContextConfig.class};
      }
  
      @Override
      protected String[] getServletMappings() {   
          return new String[] {"/"};
      }
  
  }
  </code></pre>
  
  <p>and pom.xml:</p>
  
  <pre><code>&lt;project xmlns="http://maven.apache.org/POM/4.0.0"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"&gt;
      &lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt;
      &lt;groupId&gt;com.foxminded.tasks&lt;/groupId&gt;
      &lt;artifactId&gt;University1&lt;/artifactId&gt;
      &lt;version&gt;0.0.1-SNAPSHOT&lt;/version&gt;
      &lt;name&gt;University1&lt;/name&gt;
      &lt;properties&gt;
          &lt;maven.compiler.target&gt;11&lt;/maven.compiler.target&gt;
          &lt;maven.compiler.source&gt;11&lt;/maven.compiler.source&gt;
          &lt;junit.jupiter.version&gt;5.6.0&lt;/junit.jupiter.version&gt;
          &lt;org.springframework.version&gt;5.2.5.RELEASE&lt;/org.springframework.version&gt;
          &lt;org.springframework.boot.version&gt;2.2.6.RELEASE&lt;/org.springframework.boot.version&gt;
          &lt;h2.version&gt;1.4.200&lt;/h2.version&gt;
          &lt;org.postgres.version&gt;42.2.11&lt;/org.postgres.version&gt;
          &lt;org.sonarsource.scanner.maven.version&gt;3.2&lt;/org.sonarsource.scanner.maven.version&gt;
          &lt;mockito.version&gt;3.3.3&lt;/mockito.version&gt;
          &lt;logback.version&gt;1.3.0-alpha5&lt;/logback.version&gt;
          &lt;slf4j.version&gt;2.0.0-alpha1&lt;/slf4j.version&gt;
          &lt;servlet.version&gt;4.0.1&lt;/servlet.version&gt;
          &lt;thymeleaf.version&gt;3.0.11.RELEASE&lt;/thymeleaf.version&gt;
  
      &lt;/properties&gt;
  
      &lt;profiles&gt;
          &lt;profile&gt;
              &lt;id&gt;sonar&lt;/id&gt;
              &lt;activation&gt;
                  &lt;activeByDefault&gt;true&lt;/activeByDefault&gt;
              &lt;/activation&gt;
              &lt;properties&gt;
                  &lt;sonar.host.url&gt;
                      http://localhost:9000
                  &lt;/sonar.host.url&gt;
              &lt;/properties&gt;
          &lt;/profile&gt;
      &lt;/profiles&gt;
  
      &lt;dependencies&gt;
          &lt;dependency&gt;
              &lt;groupId&gt;org.springframework&lt;/groupId&gt;
              &lt;artifactId&gt;spring-jdbc&lt;/artifactId&gt;
              &lt;version&gt;${org.springframework.version}&lt;/version&gt;
          &lt;/dependency&gt;
          &lt;dependency&gt;
              &lt;groupId&gt;org.springframework&lt;/groupId&gt;
              &lt;artifactId&gt;spring-context&lt;/artifactId&gt;
              &lt;version&gt;${org.springframework.version}&lt;/version&gt;
          &lt;/dependency&gt;
          &lt;dependency&gt;
              &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
              &lt;artifactId&gt;spring-boot-starter-logging&lt;/artifactId&gt;
              &lt;version&gt;${org.springframework.boot.version}&lt;/version&gt;
          &lt;/dependency&gt;
          &lt;dependency&gt;
              &lt;groupId&gt;org.springframework&lt;/groupId&gt;
              &lt;artifactId&gt;spring-test&lt;/artifactId&gt;
              &lt;version&gt;${org.springframework.version}&lt;/version&gt;
              &lt;scope&gt;test&lt;/scope&gt;
          &lt;/dependency&gt;
          &lt;dependency&gt;
              &lt;groupId&gt;org.springframework&lt;/groupId&gt;
              &lt;artifactId&gt;spring-web&lt;/artifactId&gt;
              &lt;version&gt;${org.springframework.version}&lt;/version&gt;
          &lt;/dependency&gt;
          &lt;dependency&gt;
              &lt;groupId&gt;org.springframework&lt;/groupId&gt;
              &lt;artifactId&gt;spring-webmvc&lt;/artifactId&gt;
              &lt;version&gt;${org.springframework.version}&lt;/version&gt;
          &lt;/dependency&gt;
          &lt;dependency&gt;
              &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
              &lt;artifactId&gt;spring-boot-starter-web&lt;/artifactId&gt;
              &lt;version&gt;2.2.7.RELEASE&lt;/version&gt;
          &lt;/dependency&gt;
          &lt;dependency&gt;
              &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
              &lt;artifactId&gt;spring-boot-starter-thymeleaf&lt;/artifactId&gt;
              &lt;version&gt;2.2.7.RELEASE&lt;/version&gt;
          &lt;/dependency&gt;
  
          &lt;dependency&gt;
              &lt;groupId&gt;org.thymeleaf&lt;/groupId&gt;
              &lt;artifactId&gt;thymeleaf-spring5&lt;/artifactId&gt;
              &lt;version&gt;${thymeleaf.version}&lt;/version&gt;
          &lt;/dependency&gt;
          &lt;dependency&gt;
              &lt;groupId&gt;org.springframework&lt;/groupId&gt;
              &lt;artifactId&gt;spring-core&lt;/artifactId&gt;
              &lt;version&gt;${org.springframework.version}&lt;/version&gt;
          &lt;/dependency&gt;
          &lt;dependency&gt;
              &lt;groupId&gt;org.springframework&lt;/groupId&gt;
              &lt;artifactId&gt;spring-beans&lt;/artifactId&gt;
              &lt;version&gt;${org.springframework.version}&lt;/version&gt;
          &lt;/dependency&gt;
          &lt;dependency&gt;
              &lt;groupId&gt;javax.servlet&lt;/groupId&gt;
              &lt;artifactId&gt;javax.servlet-api&lt;/artifactId&gt;
              &lt;version&gt;${servlet.version}&lt;/version&gt;
              &lt;scope&gt;provided&lt;/scope&gt;
          &lt;/dependency&gt;
          &lt;dependency&gt;
              &lt;groupId&gt;com.h2database&lt;/groupId&gt;
              &lt;artifactId&gt;h2&lt;/artifactId&gt;
              &lt;version&gt;${h2.version}&lt;/version&gt;
              &lt;scope&gt;test&lt;/scope&gt;
          &lt;/dependency&gt;
          &lt;dependency&gt;
              &lt;groupId&gt;org.junit.jupiter&lt;/groupId&gt;
              &lt;artifactId&gt;junit-jupiter-engine&lt;/artifactId&gt;
              &lt;version&gt;${junit.jupiter.version}&lt;/version&gt;
              &lt;scope&gt;test&lt;/scope&gt;
          &lt;/dependency&gt;
          &lt;dependency&gt;
              &lt;groupId&gt;org.mockito&lt;/groupId&gt;
              &lt;artifactId&gt;mockito-core&lt;/artifactId&gt;
              &lt;version&gt;${mockito.version}&lt;/version&gt;
              &lt;scope&gt;test&lt;/scope&gt;
          &lt;/dependency&gt;
          &lt;dependency&gt;
              &lt;groupId&gt;org.mockito&lt;/groupId&gt;
              &lt;artifactId&gt;mockito-junit-jupiter&lt;/artifactId&gt;
              &lt;version&gt;${mockito.version}&lt;/version&gt;
              &lt;scope&gt;test&lt;/scope&gt;
          &lt;/dependency&gt;
          &lt;dependency&gt;
              &lt;groupId&gt;org.sonarsource.scanner.maven&lt;/groupId&gt;
              &lt;artifactId&gt;sonar-maven-plugin&lt;/artifactId&gt;
              &lt;version&gt;${org.sonarsource.scanner.maven.version}&lt;/version&gt;
          &lt;/dependency&gt;
          &lt;dependency&gt;
              &lt;groupId&gt;org.postgresql&lt;/groupId&gt;
              &lt;artifactId&gt;postgresql&lt;/artifactId&gt;
              &lt;version&gt;${org.postgres.version}&lt;/version&gt;
          &lt;/dependency&gt;
          &lt;dependency&gt;
              &lt;groupId&gt;org.slf4j&lt;/groupId&gt;
              &lt;artifactId&gt;slf4j-api&lt;/artifactId&gt;
              &lt;version&gt;${slf4j.version}&lt;/version&gt;
          &lt;/dependency&gt;
          &lt;dependency&gt;
              &lt;groupId&gt;ch.qos.logback&lt;/groupId&gt;
              &lt;artifactId&gt;logback-classic&lt;/artifactId&gt;
              &lt;version&gt;${logback.version}&lt;/version&gt;
          &lt;/dependency&gt;
          &lt;dependency&gt;
              &lt;groupId&gt;ch.qos.logback&lt;/groupId&gt;
              &lt;artifactId&gt;logback-core&lt;/artifactId&gt;
              &lt;version&gt;${logback.version}&lt;/version&gt;
          &lt;/dependency&gt;
      &lt;/dependencies&gt;
  
  &lt;/project&gt;
  </code></pre>
  
  <p>please, can u explain, where is problem and what can i do. I tried to delete .m2 repository and rebuild project, but nothing was happend.</p>
  
  <p>main method i didn change from creating dao and service layer, its make little menu in console for getting time table for students and teachers:</p>
  
  <pre><code>public class Main {
  
      private final static Logger logger = LoggerFactory.getLogger(Main.class);
  
      public static void main(String[] args) {
          logger.info("Start Main");
  
          @SuppressWarnings("resource")
          final ApplicationContext context = new AnnotationConfigApplicationContext(ContextConfig.class);     
          DatabaseInitializer initializer = context.getBean("databaseInitializer", DatabaseInitializer.class);
          try {
              initializer.createTableInsertData();
          } catch (IOException e1) {
              logger.error("DB was not created");
              System.exit(0);
          }
          TimeTable timeTable = context.getBean("timeTable", TimeTable.class);
          TeacherService teacherService = context.getBean("teacherService", TeacherService.class);
          StudentService studentService = context.getBean("studentService", StudentService.class);    
  
          final BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));     
          final String commandListMessage = "Please select which TimeTable you want take:\n"
                  + "\"1\" - TimeTable for student for selected interval;\n"
                  + "\"2\" - TimeTable for teacher for selected interval;\n"
                  + "\"help\" - for get this list of commands again;\n" + "or \"exit\" to exit.";
  
          System.out.println(commandListMessage);
  
          String command = "";
  
          try {
              command = reader.readLine();        
              logger.debug("command is {}", command);         
              logger.debug("start menu loop");
              while (!(command.equalsIgnoreCase("exit"))) {
                  logger.info("switch command");              
                  switch (command) {
                  case "1":
                      logger.debug("case 1");         
                      System.out.println("Enter student id:");
                      int studentId = Integer.parseInt(reader.readLine());
                      Student student = studentService.findOne(studentId);
  
                      if (student != null) {
                          System.out.println("Enter date interval as \"MM.DD-MM.DD\":");
                          String[] dateInterval = reader.readLine().split("\\D");     
                          logger.debug("getting TT for student {} and period {}.{}-{}.{}", student, dateInterval[0], dateInterval[1], dateInterval[2], dateInterval[3]);                      
                          String timeTableString = timeTable.getTTForGroup(student,
                                  LocalDateTime.of(Year.now().getValue(), Month.of(Integer.parseInt(dateInterval[0])),
                                          Integer.parseInt(dateInterval[1]), 0, 0, 0),
                                  LocalDateTime.of(Year.now().getValue(), Month.of(Integer.parseInt(dateInterval[2])),
                                          Integer.parseInt(dateInterval[3]), 23, 59, 59));
                          timeTable.printTimeTable(timeTableString);
                      } else {
                          System.out.println("student whith this id \"" + studentId + "\" is not exist.");                        
                          logger.warn("student with this id {} is not exist", studentId);
                      }
  
                      break;
                  case "2":
                      logger.debug("case 2");                 
                      System.out.println("Enter teacher id:");
                      int teacherId = Integer.parseInt(reader.readLine());
                      Teacher teacher = teacherService.findOne(teacherId);
  
                      if (teacher != null) {
                          System.out.println("Enter date interval as \"MM.DD-MM.DD\":");
                          String[] dateInterval = reader.readLine().split("\\D");             
                          logger.debug("getting TT for teacher {} and period {}.{}-{}.{}", teacher, dateInterval[0], dateInterval[1], dateInterval[2], dateInterval[3]);                  
                          String timeTableString = timeTable.getTTForTeacher(teacher,
                                  LocalDateTime.of(Year.now().getValue(), Month.of(Integer.parseInt(dateInterval[0])),
                                          Integer.parseInt(dateInterval[1]), 0, 0, 0),
                                  LocalDateTime.of(Year.now().getValue(), Month.of(Integer.parseInt(dateInterval[2])),
                                          Integer.parseInt(dateInterval[3]), 23, 59, 59));
                          timeTable.printTimeTable(timeTableString);
                      } else {
                          System.out.println("teacher whith this id \"" + teacherId + "\" is not exist.");                        
                          logger.warn("teacher with this id {} is not exist", teacherId);
                      }
  
                      break;
                  case "help":
                      logger.debug("case help");
                      System.out.println(commandListMessage);
                      break;
                  default:
                      logger.debug("case default");
                      System.out.println("Please enter the correct command.");
                      break;
                  }
                  command = reader.readLine();
              }
              reader.close();
          } catch (IOException e) {
              logger.error("Reading failure", e);
          }   
          logger.info("Exit Main");
      }
  
  }
  </code></pre>