This guide describes a couple of models, by which a components refers to services.
A component can reference services provided by other components or bundles in the framework by using one of the following models:
Lookup Model
To reference a service using this model:
HelloServiceReference class component description
The code example snippet below contains a component's implementation class which references the service provided by the component introduced in the "Providing a Service" section.
How to reference a service using the Lookup model is shown below:
package simple.service.reference;
import org.osgi.service.component.ComponentContext;
import simple.service.HelloService;
public class HelloServiceReference {
protected ComponentContext context;
HelloService helloService;
protected void activate(ComponentContext ctxt){
this.context = ctxt;
helloService = (HelloService) ctxt.locateService("helloService");
helloService.hello();
}
protected void deactivate(ComponentContext ctxt){
this.context = null;
}
}
And the component description is as follows:
<?xml version="1.0" encoding="UTF-8"?>
<scr:component name="HelloServiceReference"
xmlns:scr="http://www.osgi.org/xmlns/scr/v1.0.0">
<implementation class="simple.service.reference.HelloServiceReference"/>
<reference name="helloService"
interface="simple.service.HelloService"
/>
</scr:component>
Event Model
To obtain a service using this model:
The SCR passes the referenced service as an argument of the bind and unbind methods.
The listing below contains a class which implements bind (setHelloService) and unbind (unsetHelloService) methods to obtain the service provided by the component introduced in the Providing a Service section:
The following example uses Event model for referencing a service:
package simple.service.reference;
import simple.service.HelloService;
public class HelloServiceBind {
HelloService helloService;
public void setHelloService(HelloService helloService){
this.helloService = helloService;
helloService.hello();
}
public void unsetHelloService(HelloService helloSerivce){
this.helloService = null;
}
}
The XML description of the HelloServiceBind component you can find in the snippet below:
<?xml version="1.0" encoding="UTF-8"?>
<scr:component name="HelloServiceBind" xmlns:scr="http://www.osgi.org/xmlns/scr/v1.0.0">
<implementation class="simple.service.reference.HelloServiceBind"/>
<reference name="helloService"
interface="simple.service.HelloService"
bind="setHelloService"
unbind="unsetHelloService"
/>
</scr:component>
Disclaimer
The above information is only a small subset of the functionality provided by the OSGi Specification.