Java – Register a Servlet in Spring Boot

The below code shows you how to register a Servlet in Spring Boot application via ServletRegistrationBean bean.
package com.bytenota.springboot;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;

import com.bytenota.springboot.web.MyServlet;

public class SpringBootWebApplication {
   public static void main(String[] args) {, args);
   ServletRegistrationBean myServletRegistration () {
     ServletRegistrationBean srb = new ServletRegistrationBean();
     srb.setServlet(new MyServlet());
     return srb;

In the above code, we have registered MyServlet and add URL mapping (/my-servlet) for it.

Leave a Reply