Spring Boot不尊重@WebServlet

Jas*_*son 11 spring annotations servlet-3.0 spring-boot embedded-tomcat-8

我创建了一个Servlet(从HttpServlet扩展)并按照3.0规范注释

@WebServlet(name="DelegateServiceExporter", urlPatterns={"/remoting/DelegateService"})
Run Code Online (Sandbox Code Playgroud)

@Configuration在Spring Boot中的类扫描这个servlet的包.但是,当我的Spring Boot应用程序启动时,它没有记录它已在嵌入式Tomcat 8.0.15容器中部署此servlet.

所以,我也加入@Component了我的servlet.现在,Spring Boot注册了servlet(向我证明扫描包已正确设置),但随后它使用驼峰大小写基于类名的URL模式进行注册.所以,这更好 - 例如,我注册了一个servlet,但是URL映射错误!

2015-01-05 11:29:08,516 INFO  (localhost-startStop-1) [org.springframework.boot.context.embedded.ServletRegistrationBean] Mapping servlet: 'delegateServiceExporterServlet' to [/delegateServiceExporterServlet/]
Run Code Online (Sandbox Code Playgroud)

如何让Spring Boot自动加载所有带@WebServlet注释的servlet并遵守其url映射?

小智 25

添加@ServletComponentScan你的bootstrap类.

@SpringBootApplication
@ServletComponentScan 
public class Application {
   public static void main(String[] args) {
       SpringApplication.run(Application.class, args);
   }
}
Run Code Online (Sandbox Code Playgroud)

这将使弹簧启动扫描@WebServlet以及@WebListener.

  • 我建议指定 Java 包以避免扫描整个依赖关系树;例如,@ServletComponentScan(“org.my.project.servlet”) (2认同)

Jea*_*ond 5

使用Spring Boot,如果要注册Servlet并提供URL模式,则应使用ServletRegistrationBean对象而不是@WebServlet注释.

将此bean添加到您的@Configuration类应该可以做到这一点:

@Bean
public ServletRegistrationBean delegateServiceExporterServlet() {
    return new ServletRegistrationBean(new DelegateServiceExporter(), "/remoting/DelegateService");
}
Run Code Online (Sandbox Code Playgroud)


use*_*501 5

可以@WebServlet在 Spring Boot 中加载带有注释的 servlet 及其映射。为此,您需要使用@ServletComponentScan注释@Configuration。这也适用于@WebFilter@WebListener注释。


归档时间:

查看次数:

7342 次

最近记录:

9 年,8 月 前