I have a servlet to which I need to supply dependencies via autowiring (it's a class from an external library, I cannot change its code). I try to register it as a bean and later register it using programmatic registration (ServletContextInitializer
). Here is what I have:
@Configuration
public class MyConfiguration {
@Bean
public MyServlet myServlet() {
return new MyServlet();
}
}
Also, SpringMVC-related autoconfiguration creates a usual DispatcherServlet
and maps it at /
.
When I try to start the application, I get the following:
Caused by: java.lang.IllegalStateException: Multiple servlets map to path /: dispatcherServlet[mapped:JAVAX_API:null],myServlet[mapped:JAVAX_API:null]
So it looks like Spring Boot (or Spring itself?) automatically maps the servlet at the default /
. I would like to avoid the mapping at all as I just need to create the servlet instance; I will register it myself later.
Can this be done?
答案 0 :(得分:1)
you should use a ServletRegistrationBean
then you can provide an extra mapping
@Bean
public MyServlet myServlet() {
return new MyServlet();
}
@Bean
public ServletRegistrationBean myServletRegistration(MyServlet myServlet) {
ServletRegistrationBean registration = new ServletRegistrationBean(myServlet,
"/myservlet/*");
registration.setLoadOnStartup(1);
return registration;
}