- springboot версии 3.3.5
- Отредактирован вопрос, удален ServletContext и использован appContext.setParent с Spring ApplicationContext
Однако я заметил, что, хотя мой WebMvcConfigurer создается (я добавил регистрацию в конструкторе), функция addInterceptors не работает. Не казнен. Возможно, это связано с тем, что я исключил WebMvcAutoConfiguration.class, но если я не исключаю, я получу следующую ошибку:
Error creating bean with name 'resourceHandlerMapping' defined in class path resource [org/springframework/boot/autoconfigure/web/servlet/WebMvcAutoConfiguration$EnableWebMvcConfiguration.class]: Failed to instantiate [org.springframework.web.servlet.HandlerMapping]: Factory method 'resourceHandlerMapping' threw exception with message: No ServletContext set
Ниже мой код:
@SpringBootApplication(exclude = ServletWebServerFactoryAutoConfiguration.class)
@ComponentScan({"mynamespace"})
@EnableAutoConfiguration(exclude = {QuartzAutoConfiguration.class, WebMvcAutoConfiguration.class})
public class MySpringBootContainer {
@Autowired
ApplicationContext applicationContext;
private static final Logger log = LoggerFactory.getLogger(MySpringBootContainer.class);
public static void main(String[] args) {
SpringApplication app = new SpringApplication(SpringBootContainer.class);
app.setDefaultProperties(Map.of(
"spring.config.import", "file:./config.yml")
);
app.run(args);
}
@Bean
public TomcatServletWebServerFactory tomcatFactory() {
TomcatServletWebServerFactory factory = new TomcatServletWebServerFactory() {
@Override
protected TomcatWebServer getTomcatWebServer(Tomcat tomcat) {
Context webContext = tomcat.addContext("/test1", null);
Context webContext2 = tomcat.addContext("/test2", null);
AnnotationConfigWebApplicationContext appContext = new AnnotationConfigWebApplicationContext();
appContext.setParent(applicationContext);
appContext.scan("mynamespace");
appContext.refresh();
tomcat.getHost().removeChild(tomcat.getHost().findChild("")); // remove default app context
var dispatcherServlet = new DispatcherServlet(appContext);
dispatcherServlet.setDetectAllHandlerAdapters(true);
dispatcherServlet.setDetectAllHandlerExceptionResolvers(true);
dispatcherServlet.setDetectAllHandlerMappings(true);
dispatcherServlet.setDetectAllViewResolvers(true);
Tomcat.addServlet(webContext, "default", dispatcherServlet);
webContext.addServletMappingDecoded("/*", "default");
var dispatcherServlet2 = new DispatcherServlet(appContext);
Tomcat.addServlet(webContext2, "default", dispatcherServlet2);
webContext2.addServletMappingDecoded("/*", "default");
return super.getTomcatWebServer(tomcat);
}
});
return factory;
}
}
Подробнее здесь: https://stackoverflow.com/questions/791 ... springboot