Sprint Boot Servlet Registration on a different port

Viewed 181

I have a spring-boot application with a @RestController, and need to register a servlet on a different port, while the RestController is bound to the default port.

I have an application.yml file and a src>main>resources>application.properties file.

This is my Servlet registration class

@Configuration
public class ServletConfig {
    private static final Logger LOGGER = LoggerFactory.getLogger (ServletConfig.class);

    @Bean
    public ServletRegistrationBean<MyServlet> servletRegistrationBean(final ServletContext servletContext){
        LOGGER.info("Inside ServletRegistrationBean");
        final ServletRegistrationBean <MyServlet> bean = new ServletRegistrationBean <> (new MyServlet (), true, "/endpoint");
        bean.setLoadOnStartup (1);
        return bean;
    }

Here is my MyServlet class:

public class MyServlet extends AbstractXServlet{ private static final Logger LOGGER = LoggerFactory.getLogger (MyServlet.class);

public MyServlet() {
    LOGGER.info("Inside MyServlet Constructor");
    settings().setMultipartEnabled(false);
    final ServletHandlerr servletHandlerr = new ServletHandlerr();
    
    //Http POST Only
    handlerRegistry().registerHandler(EHttpMethod.POST, servletHandlerr);
}

}

I want to define the port for the servlet on my application.properties file, different than the default port where all the RestController endpoints are. But right now, I can't get to print any of the log messages. Not sure what i'm doing wrong. Any help is really appreciated.

1 Answers

I want to define the port for the servlet on my application.properties file, different than the default port where all the RestController endpoints are

...which essentially means you want to have a separate web server, running on a different port than the rest of the application. Personally, I would create a completely separate SpringBootApplication for that purpose.

However, if you insist on bundling it together in a single app, you could create an additional embedded container that does not register the default servlet (.setRegisterDefaultServlet(false)) and instead only registers your custom servlet.

You will need to make sure your custom factory does not override the usual auto-configuration of the embedded container that the rest of the app will be bound to. You might need to duplicate parts of the original ServletWebServerFactoryConfiguration of the default servlet, and mark it @Primary to distinguish it from your custom servlet container.

Related