SoFunction
Updated on 2025-05-20

Four ways to inject Service into Servlet in Spring

Method 1: Use @WebServlet and @Autowired

If you are using Servlet 3.0+ specification, you can use it directly@WebServletAnnotation to declare the Servlet and pass@AutowiredInject Service.

Implementation steps:

  1. Configuring Servlet Scan Support
    Make sure your project has Spring component scanning enabled, as well as Spring's integrated configuration with Servlet containers (such as through@SpringBootApplicationor manually configure Spring context).

  2. Define Service Class

@Service
public class MyService {
    public String process() {
        return "Service processing...";
    }
}
  • Define Servlet class
@WebServlet(name = "myServlet", urlPatterns = "/myServlet")
public class MyServlet extends HttpServlet {

    @Autowired
    private MyService myService;

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String result = ();
        ().write("Result from service: " + result);
    }
}
  • Spring configuration (optional)

If using Spring Boot, make sure@SpringBootApplicationAlready enabled@ServletComponentScan,as follows:

@SpringBootApplication
@ServletComponentScan
public class MyApplication {
    public static void main(String[] args) {
        (, args);
    }
}

Method 2: Register the Servlet through @Bean and inject dependencies

If you don't want to use@WebServletAnnotation can be done through Spring@ConfigurationRegister the Servlet as a Spring Bean into the Servlet container.

Implementation steps:

  • Define Service Class
@Service
public class MyService {
    public String process() {
        return "Service processing...";
    }
}
  • Define Servlet class
public class MyServlet extends HttpServlet {

    private final MyService myService;

    public MyServlet(MyService myService) {
         = myService;
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String result = ();
        ().write("Result from service: " + result);
    }
}
  • Configure Servlet Registration
    In the Spring configuration class, register the Servlet bean and inject the Service:
@Configuration
public class ServletConfig {

    @Bean
    public ServletRegistrationBean<MyServlet> myServletRegistration(MyService myService) {
        return new ServletRegistrationBean<>(new MyServlet(myService), "/myServlet");
    }
}

Method 3: Through @Component and SpringBeanAutowiringSupport

If you are using a traditional servlet (such asServlet defined in SpringSpringBeanAutowiringSupportEnable dependency injection manually.

Implementation steps:

  • Define Service Class
@Service
public class MyService {
    public String process() {
        return "Service processing...";
    }
}
  • Define Servlet class
public class MyServlet extends HttpServlet {

    @Autowired
    private MyService myService;

    @Override
    public void init() throws ServletException {
        ();
        (this);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String result = ();
        ().write("Result from service: " + result);
    }
}
  • Configuring Servlet Container
    If using, add Servlet configuration:
<servlet>
    <servlet-name>myServlet</servlet-name>
    <servlet-class></servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>myServlet</servlet-name>
    <url-pattern>/myServlet</url-pattern>
</servlet-mapping>
  • Spring Context Configuration
    Make sure your Spring context is loaded into the Servlet container, for exampleDefine Spring Listener in:
<listener>
    <listener-class></listener-class>
</listener>
<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/</param-value>
</context-param>

Method 4: Spring Boot and ServletRegistrationBean

If you are using Spring Boot, it is recommended to use itServletRegistrationBeanTo implement Servlet registration and inject dependencies.

Implementation steps:

  • Define Service Class
@Service
public class MyService {
    public String process() {
        return "Service processing...";
    }
}
  • Define Servlet class
public class MyServlet extends HttpServlet {

    private final MyService myService;

    public MyServlet(MyService myService) {
         = myService;
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String result = ();
        ().write("Result from service: " + result);
    }
}
  • Configure Servlet Registration
    In the Spring Boot configuration class, register the Servlet:
@Configuration
public class ServletConfig {

    @Bean
    public ServletRegistrationBean<MyServlet> myServletRegistration(MyService myService) {
        return new ServletRegistrationBean<>(new MyServlet(myService), "/myServlet");
    }
}
  • Run the application
    Run the application through Spring Boot startup class:
@SpringBootApplication
public class MyApplication {
    public static void main(String[] args) {
        (, args);
    }
}

Summarize

The above four methods can select suitable solutions based on project requirements and technology stack:

  1. If using@WebServlet, use directly@Autowiredannotation.
  2. If more flexible control is required, you canServletRegistrationBeanRegister a Servlet.
  3. If using traditionalConfiguration, can be usedSpringBeanAutowiringSupportImplement dependency injection.
  4. Recommended use of Spring BootServletRegistrationBeanServlet registration.

In actual development, using Spring Boot can simplify the configuration process and is a preferred solution!

This is the article about four methods of injecting Service into Servlets in Spring. For more related content to inject Spring Service into Servlets, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!