Java Reference
In-Depth Information
Listing 6.4
Declaring special offer service that has an
Inventory
dependency
<?xml version='1.0' encoding='utf-8'?>
<component name='fancyfoods.cheese.offer' enabled='true'>
<implementation
class='fancyfoods.department.cheese.offers.DesperateCheeseOffer'/
>
<service>
<provide interface='fancyfoods.offers.SpecialOffer'/>
</service>
Expose this
component
as service
<reference name='inventory' interface='fancyfoods.food.Inventory'
bind='setInventory' unbind='unsetInventory' />
</component>
Inject Inventory instance using
named set and unset methods
Because it's an older technology than Blueprint, Declarative Services has a wider
range of tooling support. Some of the more popular tools, such as bnd and bndtools,
support both of them, which makes it convenient to use whichever dependency injec-
tion technology you prefer. (More on bnd can be found in chapter 8.)
ANNOTATIONS
One limitation of both Declarative Services and Blueprint is that, in their original,
strictly specified forms, neither supported annotations. Annotations are a frequent
feature request for both Declarative Services and Blueprint, and unofficial support
has been developed for both platforms. Annotation support for Blueprint has been
prototyped in Apache Aries, but not developed further at the time of writing. Anno-
tation support for Declarative Services is available in Apache Felix's
SCR
subproject.
The
SCR
support has now been standardized. As well as being more concise than
XML
metadata (which isn't hard!), annotations are less brittle if you refactor your
code frequently.
Felix's annotation support works by using a Maven plug-in to convert the annotations
to normal Declarative Services
XML
at compile time. To use the support, you'll first need
to add a Maven dependency on the
maven-scr-plugin
. The annotation syntax is rich,
supporting almost everything that can be specified in
DS
XML
, but in its simplest form,
to identify a class as a component and expose it as a service, you'd write this:
@Component
@Service
public class DesperateCheeseOffer implements SpecialOffer {
To inject a reference to another service, it's even simpler:
@Reference
Inventory inventory;
Handy as it is, the Felix
SCR
annotation support does feel slightly tacked-on. Although
Declarative Services is part of the existing
OSG
i specifications, annotations aren't
(although there are plans to add them soon). Other dependency injection frame-
works support both
XML
and annotations as first-class programming models.





