开发者

How should I declare a has-a dependency via OSGi declarative services?

开发者 https://www.devze.com 2023-04-05 05:07 出处:网络
My OSGi application uses a whiteboard pattern to register listeners for specific state changes. I use org.apache.felix.scr.annotations to declare my services and components instead of hand-coding the

My OSGi application uses a whiteboard pattern to register listeners for specific state changes. I use org.apache.felix.scr.annotations to declare my services and components instead of hand-coding the declarative XML. The easiest way to register my component as a ChangeListener is like so:

@Component(name="...")
@Service
public class MyComponent implements ChangeListener {
    @Override public void changeOccurred(...) {
        // ...
    }
    // ...
}

That's an is-a relationship and it exposes my component to anyone who asks for it. Instead, I want a has-a relationship to register my ChangeListener via an inner class. But the following is VERY ugly by comparison to the above.

@Component(name="...")
public class MyComponent {
    private ServiceRegistration registration;

    protected final void activate(final ComponentContext context) {
   开发者_开发百科     registration = context.getBundleContext()
               .registerService(ChangeListener.class.getName(),
        new ChangeListener() {
            @Override public void changeOccurred(...) {
                // ...
            }
        }, null);
    }
    protected final void deactivate(final ComponentContext context) {
        registration.unregister();
    }
    // ...
}

Is there a better way to implement the contained listener that's not so verbose but which still achieves the information hiding of an inner class?

0

精彩评论

暂无评论...
验证码 换一张
取 消