Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dependency injection in servlet on embedded Jetty

I have embedded Jetty server and I added servlet mapping.

ServletContextHandler context = new ServletContextHandler();
context.setContextPath("/");
context.addServlet(RegisterServlet.class, "/user/register");

I want to make the Dependency Injection in servlet with spring framework configuring ApplicationContext.xml. It should work the same as here:

public class RegisterServlet extends HttpServlet {
private Service service;
@Override
public void init() throws ServletException {
    super.init();
    ApplicationContext context = new ClassPathXmlApplicationContext("ApplicationContext.xml");
    service = context.getBean("service", Service.class);
}

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    ...
}

but without using context.getBean("service").

like image 931
anton Avatar asked Jul 26 '15 17:07

anton


People also ask

What is embedded Jetty?

Put another way, running Jetty in embedded mode means putting an HTTP module into your application, rather than putting your application into an HTTP server.

Is Jetty a servlet container?

Eclipse Jetty is a Java web server and Java Servlet container. While web servers are usually associated with serving documents to people, Jetty is now often used for machine to machine communications, usually within larger software frameworks.

What is Jetty servlet?

What Is Jetty Server? Jetty is an open source Java web server, as well as a servlet container, that provides an application with the features required to launch and run an application servlet or API.


1 Answers

This way you can have the control of servlet instantiation

Server server = new Server(port);
ServletHandler handler = new ServletHandler();
handler.addServletWithMapping(new ServletHolder(new RegisterServlet()), "/user/register");
server.setHandler(handler);
server.start();

So now you can get the servlet instance from a DI container of something

like image 176
apflieger Avatar answered Sep 25 '22 14:09

apflieger