Dependency Manager - Aspect

Aspects, as part of aspect oriented programming, can be used in a dynamic environment such as OSGi to "extend" existing services and add certain "capabilities" to them. Examples of these are adding a specific caching mechanism to a storage service or implementing logging. Aspects in OSGi can be applied to services and can be added and removed at runtime.

To define an aspect component, you need to create an AspectComponent component using the DependencyActivatorBase.createAspectComponent() or the DependencyManager.createAspectComponent() method. This interface extends the Component interface in order to add extra setters methods needed to define an aspect service component.

Usage example:

In this example, a "DatabaseCache" aspect service is used to add caching functionality to an existing Database service. Here is the DatabaseCache aspect service will sit between any Database service consumer and the original Database service:

interface Database {
    String get(String key);
}

public class Activator extends DependencyActivatorBase {
     &Override
     public void init(BundleContext context, DependencyManager dm) throws Exception {
         Component aspectComponent = createAspectComponent()
             .setAspect(Database.class, null, 10)
             .setImplementation(DatabaseCache.class)
             .add(createServiceDependency().setService(LogService.class).setRequired(false));
         dm.add(aspectComponent);
     }
}