ServletContextAware bean getting initialized too early when using @SpringBootTest with @AutoConfigureMockMvc

Viewed 129

I'm seeing an odd issue when using @SpringBootTest with @AutoConfigureMockMvc. I have a SpringBoot project setup with an application.yaml file that provides a custom server.servlet.context-path, this value is used in a platform layer, using a ServletContextAware bean, to get context information for creating an Open API specification. When the application is launched normally, everything works as expected. The ServletContext is updated with context path in ServerProperties.setContextPath(), then setServletContext() is called on my bean. When it is run via a JUnit, this happens in reverse order. I first see setServletContext() called on my bean before the application.yaml data is loaded and I do not get the updated context path.

Spring Boot App

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

application.yaml

server.servlet.context-path: /some/custom/path

Servlet context aware configuration bean

@Configuration
@EnableSwagger2
public class SwaggerConfiguration implements ServletContextAware {

    ...

    public void setServletContext(@NonNull ServletContext servletContext) {
        this.servletContext = servletContext;
    }
}

JUnit

@SpringBootTest(classes = {Application .class})
@AutoConfigureMockMvc
public class ApplicationTest {

    @Autowired
    private MockMvc mockMvc;

    ...
}
0 Answers
Related