RSS

Search Engine

Sunday, July 18, 2010

Using services via declarative services

Of course you can also define the consumption of services via DS.

Create a new plugin "de.vogella.osgi.ds.quoteconsumer". Do now 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;
}
}
}

Tip

Note that this class has no dependency to OSGi.

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:

   






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:

   
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;
}
}
}

If you start is now with "start id_of_your_bundle" when you should get the feedback that the service was set and one quote should be returned.

0 comments:

Post a Comment