将所有HttpRequestHandlerServlet从web.xml移动到Spring Boot

时间:2019-11-26 12:52:24

标签: java spring spring-boot servlets web.xml

我的web.xml具有以下servlet:

  <servlet>
    <servlet-name>noteService</servlet-name>
    <servlet-class>org.springframework.web.context.support.HttpRequestHandlerServlet</servlet-class>
  </servlet>

  <servlet>
    <servlet-name>addressService</servlet-name>
    <servlet-class>org.springframework.web.context.support.HttpRequestHandlerServlet</servlet-class>
  </servlet>

  <servlet>
    <servlet-name>refDataService</servlet-name>
    <servlet-class>org.springframework.web.context.support.HttpRequestHandlerServlet</servlet-class>
  </servlet>

  .
  .
  .
  .
  .

  <servlet-mapping>
    <servlet-name>noteService</servlet-name>
    <url-pattern>/internal/noteService</url-pattern>
  </servlet-mapping>

  <servlet-mapping>
    <servlet-name>addressService</servlet-name>
    <url-pattern>/internal/addressService</url-pattern>
  </servlet-mapping>

  <servlet-mapping>
    <servlet-name>refDataService</servlet-name>
    <url-pattern>/internal/refDataService</url-pattern>
  </servlet-mapping>

我尝试在spring boot Configuration类中添加bean配置,但是它没有用:

@Bean
public ServletRegistrationBean httpRequestHandlerServletRegistration() {
    ServletRegistrationBean registration = new ServletRegistrationBean(new HttpRequestHandlerServlet());
    registration.addUrlMappings("/internal/noteService", "/internal/addressService",
            "/internal/refDataService");
    return registration;
}

得到以下问题:

org.springframework.beans.factory.BeanNotOfRequiredTypeException: Bean named 'httpRequestHandlerServlet' is expected to be of type 'org.springframework.web.HttpRequestHandler' but was actually of type 'org.springframework.boot.web.servlet.ServletRegistrationBean'
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:392)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:204)
    at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1111)
    at org.springframework.web.context.support.HttpRequestHandlerServlet.init(HttpRequestHandlerServlet.java:60)
    at javax.servlet.GenericServlet.init(GenericServlet.java:158)

从错误日志中,看来我必须像这样分别定义每个bean:

  @Bean(name = "/noteService")
  public HttpRequestHandler noteService() {
      return new HttpRequestHandler();
  }

在此应用程序中,我大约有25种不同的servlet映射URL模式,它们都指向同一个HttpRequestHandlerServlet。

此问题的最佳解决方案是什么?

0 个答案:

没有答案