If you use the installer to depend on the service, as you have shown, it can work outside of OSGi. You just need to use some other dependency injection mechanism. If not, you can provide a subclass that initializes the servlet using JNDI lookup or from the servlet context.
public class MyServlet_AdapterForMissingDI extends MyServlet{ public void init(ServletConfig config){ setFooService(getItFromSomewhere()); } }
The thing is, if you have DI capabilities that can setFooService can embed, you can just use the same servlet in OSGi and in other places, if you havenβt (and still want to support this case), you provide an adapter.
Check the Felix SCR in the corresponding note to configure dependencies between objects and the Pax Web Extender board, which will take care of connecting your servlet to the HttpService.
In particular, without SCR and Whiteboard, you need to think about the case when fooService becomes unavailable later, or HttpService starts after your servlet. In these cases, your servlet will refer to a dead service that prevents garbage collection, or your servlet will not be registered with the HttpService.
Update: Here is the SCR handle that I use for one of my servlets. SCR handles the servlet instance, life cycle, registration (through the board), and dependencies. There is no OSGi code in the servlet. There is no longer a need for a BundleActivator (SCR registers all services):
<component name="oracle.statusServlet" > <implementation class="mypackage.DataSourceStatusServlet"/> <property name="service.description" value="Oracle DataSource status servlet" /> <property name="alias" value="/OracleDataSourceStatus" /> <property name="servlet-name" value="Oracle DataSource status servlet" /> <service> <provide interface="javax.servlet.Servlet" /> </service> <reference name="DATASOURCES" interface="javax.sql.DataSource" cardinality="0..n" policy="dynamic" bind="bindDataSource" unbind="unbindDataSource"/> </component>
Dependencies for the servlet are specified in the reference tag. SCR will search and bind the service.