Creating OSGi bundles
The first step of integrating an OSGi service is to create an OSGi bundle in Eclipse. You then create a Java™ interface and a Java class implementation, and you define the dependencies within the service.
Procedure
- Click File > New > Other > OSGi > OSGi Bundle Project, and then click Next.
- In the wizard, specify the name of your project.
- Optional: Clear the Add bundle to application option, and click Next twice.
- To build and deploy the service outside of the Plug-in Development Environment build, remove .qualifier from the version name, and check the Generate an activator option.
- Click Finish.
- In the src folder of your project,
right-click the package and click New > Interface to create a new Java interface. The
following example defines an AgeHelper interface:
package service.ageservice; public interface AgeHelper { public boolean isValid(int age); public void postResult(String value); }
- Create a package with a Java class
that implements the interface. The following example
creates an implementation of the AgeHelper interface
in the service.ageservice.impl package:
package service.ageservice.impl; import service.ageservice.AgeHelper; public class AgeHelperImpl implements AgeHelper { @Override public boolean isValid(int age) { System.out.println("AgeHelperImpl.isValid " + age); return age >= 18; } @Override public void postResult(String value) { System.out.println("AgeHelperImpl.postResult " + value); } }
- Optional: Edit the Activator.java file
to add traces in the start and stop methods. You can use these traces later to verify that the service is
active. For example:
public void start(BundleContext context) throws Exception { System.out.println(this.getClass().getName() + " started"); }
public void stop(BundleContext context) throws Exception { System.out.println(this.getClass().getName() + " stopped"); }
- Define the dependencies and lifecycle of the service:
- Right-click the OSGi bundle project, and click New > Other > OSGi > Blueprint file, and then click Next.
- Click Finish to close the wizard. The blueprint.xml file opens in the Design editor.
- In the Overview section, click Add, select Service and click OK. The Blueprint service wizard opens.
- For the Service interface field, click Browse and select an interface. For example, select AgeHelper.
- For the Bean Reference field, click New, then click Browse, select the relevant implementation class and click OK. For example, select the AgeHelperImpl class.
- Click OK. A new service is added in the blueprint.xml file.
- Edit the Export-Package parameter in the MANIFEST.MF file to specify a version for the service API. For example: Export-Package: service.ageservice;version="2.0.0".
Parent topic: Implementing OSGi services