| Free tutorials for Java, Eclipse and Web programming |
Of course you can also define the consumption of services via DS.
Create a new plugin "de.vogella.osgi.ds.quoteconsumer". Do not use a template, do not create an activator. Import the package "de.vogella.osgi.quote" in MANIFEST.MF on the tab "Dependencies".
Create the following class.
package de.vogella.osgi.ds.quoteconsumer;
import de.vogella.osgi.quote.IQuoteService;
public class QuoteConsumer {
private IQuoteService service;
public void quote() {
System.out.println(service.getQuote());
}
// Method will be used by DS to set the quote service
public synchronized void setQuote(IQuoteService service) {
System.out.println("Service was set. Thank you DS!");
this.service = service;
// I know I should not use the service here but just for demonstration
System.out.println(service.getQuote());
}
// Method will be used by DS to unset the quote service
public synchronized void unsetQuote(IQuoteService service) {
System.out.println("Service was unset. Why did you do this to me?");
if (this.service == service) {
this.service = null;
}
}
}
Create the Folder "OSGI-INF" and create a new "Component Definition" in this folder.

This time we will use a service. Maintain the "Referenced Services".

Make the relationship to the bind / unbind method via by selecting your entry can pressing "Edit".

The result component.xml should look like:
<?xml version="1.0" encoding="UTF-8"?> <scr:component xmlns:scr="http://www.osgi.org/xmlns/scr/v1.1.0" name="de.vogella.osgi.ds.quoteconsumer"> <implementation class="de.vogella.osgi.ds.quoteconsumer.QuoteConsumer"/> <reference bind="setQuote" cardinality="1..1" interface="de.vogella.osgi.quote.IQuoteService" name="IQuoteService" policy="static" unbind="unsetQuote"/> </scr:component>
The result MANIFEST.MF should look like:
Manifest-Version: 1.0 Bundle-ManifestVersion: 2 Bundle-Name: Quoteconsumer Bundle-SymbolicName: de.vogella.osgi.ds.quoteconsumer Bundle-Version: 1.0.4 Bundle-RequiredExecutionEnvironment: JavaSE-1.6 Import-Package: de.vogella.osgi.quote Service-Component: OSGI-INF/component.xml
Export your plugin and install it via: install file:c:\temp\bundles\plugins \de.vogella.osgi.ds.quoteconsumer.jar
"If you start the bundle now with "start id_of_your_bundle" you should get the feedback that the service was set and one quote should be returned