Saturday, January 31, 2015

[OSGi][Service] Creating a service and calling it from other bundle

Hi,

We are going to create a service, export it and import in another bundle. If you did not create a simple bundle yet, follow the post [OSGi] Hello World from OSGi | Create your first OSGi Bundle

We are going to create a classic ECHO service. Whatever is given to the service is ECHOed back to us.

After you are done creating a simple bundle HelloFromOSGi. Follow the steps below.


Step 1. Create a new bundle following the same steps to create HelloFromOSGi. Lets name that as EchoService. So the project name is me.rkg.osgi.EchoService. At this point, both bundles are same except names.

Step 2. Create an EchoService interface and EchoServiceImpl class. Lets keep them in me.rkg.osgi.

EchoService Interface 

EchoServiceImpl

Step 3. Updating Activator to register service. We will use org.osgi.framework.ServiceRegistration. We can register service with help of BundleContext which is passed to start() method.
Step 4. Updating MANIFEST.MF. We need to export the service using
Export-Package: me.rkg.osgi.echoservice.service 
Step 5. See that we export only interface not our implementations in the last step.

Step 6. Now when service is exposed, we can import into HelloFromOSGi bundle and use it. Lets modify MANIFEST.MF for HelloFromOSGi to add
Import-Package: me.rkg.osgi.echoservice.service, org.osgi.framework;version="1.3.0"
Step 7. Now we can use this service in any of the files in HelloFromOSGi. We will use org.osgi.framework.ServiceReference. We can get this reference from BundleContext passed to start() method.

Step 8. Running the bundles. You would be able to see the message.

That's it. Hope this gets you a clear idea.

Until next time :)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.