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
- 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.@SpringBootTest @AutoConfigureMockMvc public class MyControllerTest { // Your test code here }
- 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:<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency>
- Incorrect Application Type
Ensure that you’re running your application as a web application. If you’re using
SpringApplication.run()
, make sure it’s in a class annotated with@SpringBootApplication
.@SpringBootApplication public class MyApplication { public static void main(String[] args) { SpringApplication.run(MyApplication.class, args); } }
- Context Hierarchy
If you’re manually configuring Spring’s
ApplicationContext
, make sure that theWebApplicationContext
is set up correctly and is aware of theServletContext
. - 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. - 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.