Reputation: 775
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").
Upvotes: 8
Views: 826
Reputation: 1231
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
Upvotes: 2