apache-karafapache-servicemixpax-web

How to use @WebServlet and @Component in pax-web


I have a setup where I use the Pax-Web WAR-Extender so I can register servlets in standard-fashion.

Before using the WAR-Extender the servlet was a singleton where I was able to inject other osgi-references. With the extender, the services get injected due to a Declarative-Service XML but when I access the Servlet with a browser a new instance is created without injecting the other service.

@Component
@SuppressWarnings("serial")
@WebServlet(name="TestServlet", urlPatterns={"/Test"})
public class TestServlet extends HttpServlet{

    private UserDataManager userDataManager;

    public TestServlet(){
        System.out.println("------------------- New Servlet");
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession session = req.getSession();
        MbsSessionId mbsId = (MbsSessionId)session.getAttribute("MbsSessionId");

        UserData userData = userDataManager.getUserData(mbsId);         
        resp.getOutputStream().println(userData.toString());
    }

    @Reference
    void bindUserDataManager(UserDataManager userDataManager){
        this.userDataManager = userDataManager;
    }
}

My goal is to avoid calling the OSGi-Service-Registry programmatically. Is there any configuration so my Servlet is treated as a Singleton or that the OSGi-Service is re-injected?


Solution

  • The problem is you're mixing two technologies here. Pax Web does make sure Annotated Servlets are registered accordingly but doesn't know anything about DS. That's why this doesn't work at all. But if you use it in combination with Pax-CDI you're able to inject any service into your Servlet by CDI means.
    Take a look at a sample here

    This is an excerpt of it:

     @Inject
     @OsgiService
     private CookBookService cookBookService;
    

    By the way you can also configure it to be dynamic, that means Pax-CDI will take your servlet down in case the corresponding Servlet is gone. For more details on Pax Web and Pax CDI take a look at the corresponding Documentations/Projects.
    Pax Web Documentation
    Pax Web Project
    Pax CDI Project