Caused by: java.lang.IllegalStateException: No ServletContext set at org.springframework.util.Assert.state()

Troubleshooting “No ServletContext set” Error in Spring Boot

The error message Caused by: java.lang.IllegalStateException: No ServletContext set generally indicates that the Spring application context is not fully initialized, or you’re trying to use web-specific features in a non-web environment.

Common Scenarios and Solutions

  1. Incorrect Test Annotations

    If you’re facing this issue during testing, make sure you’re using the correct annotations for a Spring Boot test. For a web application, you should annotate your test class with @SpringBootTest and @AutoConfigureMockMvc or @WebMvcTest for MVC tests.

    public class MyControllerTest {
        // Your test code here
  2. Missing Spring Boot Starter Web Dependency

    Make sure you have the Spring Boot Starter Web dependency in your pom.xml if you’re using Maven:

  3. Incorrect Application Type

    Ensure that you’re running your application as a web application. If you’re using, make sure it’s in a class annotated with @SpringBootApplication.

    public class MyApplication {
        public static void main(String[] args) {
  , args);
  4. Context Hierarchy

    If you’re manually configuring Spring’s ApplicationContext, make sure that the WebApplicationContext is set up correctly and is aware of the ServletContext.

  5. Component Scanning

    Ensure that all your configuration classes are correctly scanned. If you’re using @ComponentScan, make sure it’s set up to scan all your @Configuration classes.

  6. Check for Test Configuration

    If this error is occurring during testing, check if you have any test configurations that might be conflicting with the main configuration.

By checking these areas, you should be able to identify the root cause of the issue.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.