wpgsh / cloud4water

Apache License 2.0
0 stars 0 forks source link

SCR annotations take no effect when it is used to inject AuthenticationService in the servlet #1

Closed asd1245dss closed 8 years ago

asd1245dss commented 8 years ago

@alexlukichev I create one servlet named AuthorizationServlet and I inject AuthenticationService with the @Reference annotation. image But the log tells me that the authnService object is null. image image If I use a wrong scr annotation or it needs other config?

alexlukichev commented 8 years ago

The reason for this is that there are 2 ways in this case a servlet gets registered with the framework.

1) The bundle contains Web-ContextPath parameter and thus gets processed by PAX Web Extender. This component will analyze the .ui bundle and register all resources, jsps and servlet classes annotated with @WebServlet as web app components. However such servlets will not be managed by the OSGi SCR, but rather by the Jetty container and thus injection won't work

2) SCR will also process bundle classes and will create services from the classes with @Component annotation. However these services will be different instances of servlet classes. Also due to some issue in the PAX code they will not be properly registered in the web context

There are 2 approaches to solve the problem:

1) Remove @WebServlet annotation and also rely on explicit registration with WebContainer (to work around the issue in the PAX code). This however prevents OSGI-managed servlets from being deployed within the same webapp context with the PAX managed resources. But a working solution anyway

2) Get rid of @Component annotation and use OSGi utils to resolve OSGi service dependency from inside a generic servlet code

I suggest to use the latter approach - see the committed fix. This approach can be generalized into a utility function so that there is no need to re-implement it for every servlet or service type. Another comment there is that I suggest to get a fresh instance of the service every time to ensure that we don't depend on the lifecycles of OSGi service and servlet to release the reference to the service.