How can I register a secondary servlet with Spring Boot?

后端 未结 7 679
感动是毒
感动是毒 2020-11-30 19:29

I have an extra servlet I need to register in my application. However with Spring Boot and its Java Config, I can\'t just add servlet mappings in a web.xml file

7条回答
  •  执念已碎
    2020-11-30 20:05

    If you're using embedded server, you can annotate with @WebServlet your servlet class:

    @WebServlet(urlPatterns = "/example")
    public class ExampleServlet extends HttpServlet
    

    From @WebServlet:

    Annotation used to declare a servlet.

    This annotation is processed by the container at deployment time, and the corresponding servlet made available at the specified URL patterns.

    And enable @ServletComponentScan on a base class:

    @ServletComponentScan
    @EntityScan(basePackageClasses = { ExampleApp.class, Jsr310JpaConverters.class })
    @SpringBootApplication
    public class ExampleApp 
    

    Please note that @ServletComponentScan will work only with embedded server:

    Enables scanning for Servlet components (filters, servlets, and listeners). Scanning is only performed when using an embedded web server.

    More info: The @ServletComponentScan Annotation in Spring Boot

提交回复
热议问题