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

  1. Click File > New > Other > OSGi > OSGi Bundle Project, and then click Next.
  2. In the wizard, specify the name of your project.
  3. Optional: Clear the Add bundle to application option, and click Next twice.
  4. 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.
  5. Click Finish.
  6. 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);
    }
  7. 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);
    	}
    }
  8. 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");
    	}
  9. Define the dependencies and lifecycle of the service:
    1. Right-click the OSGi bundle project, and click New > Other > OSGi > Blueprint file, and then click Next.
    2. Click Finish to close the wizard. The blueprint.xml file opens in the Design editor.
    3. In the Overview section, click Add, select Service and click OK. The Blueprint service wizard opens.
    4. For the Service interface field, click Browse and select an interface. For example, select AgeHelper.
    5. For the Bean Reference field, click New, then click Browse, select the relevant implementation class and click OK. For example, select the AgeHelperImpl class.
    6. Click OK. A new service is added in the blueprint.xml file.
    7. 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".