Difference between revisions of "OSGi Concepts Services"

From CDOT Wiki
Jump to: navigation, search
Line 21: Line 21:
 
<source lang="java">
 
<source lang="java">
 
package cs.ecl.osgi.simple.declarativeservice.say.internals;
 
package cs.ecl.osgi.simple.declarativeservice.say.internals;
 
 
 
import java.util.Date;
 
import java.util.Date;
 
 
 
import cs.ecl.osgi.simple.declarativeservice.say.Sayable;
 
import cs.ecl.osgi.simple.declarativeservice.say.Sayable;
 
  
 
public class TodaySay implements Sayable {
 
public class TodaySay implements Sayable {
 
 
 
public String say() {
 
public String say() {
 
return " Declarative Service: Today is " + new Date();
 
return " Declarative Service: Today is " + new Date();
 
}
 
}
 
}
 
}
 +
</source>
 +
 +
The relationships between the interface that is exposed to the client and the implementation that is hidden, must be defined in a xml file:
 +
 +
<source lang="xml">
 +
<?xml version="1.0"?>
 +
<component name="sayable">
 +
<implementation class="cs.ecl.osgi.simple.declarativeservice.say.internals.TodaySay"/>
 +
<service>
 +
<provide interface="cs.ecl.osgi.simple.declarativeservice.say.Sayable"/>
 +
</service>
 +
</component>
 
</source>
 
</source>

Revision as of 16:38, 21 January 2011

OSGi Services

A bundles can register and use services in OSGi. OSGi provides therefore a central registry for this purpose. A service is defined by a Java interface (POJI - Plain Old Java Interface) [1].
Access to the service registry is performed via the class BundleContext. OSGi injects the BundleContext into each bundle during the startup of the bundle. A bundle can also register itself to the BundleContext ServiceEvents which are for example triggered if a new service is installed or de-installed.

For example, let us suppose that one wants to define a service that is capable to define the day and time. For the purpose one defines an interface:

package cs.ecl.osgi.simple.declarativeservice.say;

public interface Sayable {
	String say();
}


An implementation of this interface could be:

package cs.ecl.osgi.simple.declarativeservice.say.internals;
import java.util.Date;
import cs.ecl.osgi.simple.declarativeservice.say.Sayable;

public class TodaySay implements Sayable {
	public String say() {
		return " Declarative Service: Today is " + new Date();
	}
}

The relationships between the interface that is exposed to the client and the implementation that is hidden, must be defined in a xml file:

<?xml version="1.0"?>
<component name="sayable">
	<implementation class="cs.ecl.osgi.simple.declarativeservice.say.internals.TodaySay"/>
	<service>
		<provide interface="cs.ecl.osgi.simple.declarativeservice.say.Sayable"/>
	</service>
</component>