如何在dockable中使用osgi服务?

时间:2016-03-11 11:41:13

标签: java osgi drombler-fx

如果我有一个通过注释用作可停靠窗口的类,我该如何在该类中使用osgi服务?最好的办法是将其作为私人成员。

1 个答案:

答案 0 :(得分:1)

你可以举例如。使用ServiceTracker:

import org.osgi.framework.BundleContext;
import org.osgi.framework.FrameworkUtil;
import org.osgi.framework.ServiceReference;
import org.osgi.util.tracker.ServiceTracker;
import org.osgi.util.tracker.ServiceTrackerCustomizer;
...

@ViewDocking(...)
public class MyView extends SomeNode{
    private final ServiceTracker<MyService, MyService> myServiceTracker;
    private MyService myService;

    public MyView(){
        BundleContext bundleContext = FrameworkUtil.getBundle(MyView.class).getBundleContext();
        myServiceTracker = new ServiceTracker<>(bundleContext, MyService.class,
                new MyServiceTrackerCustomizer(bundleContext));
        myServiceTracker.open(false);
    }

    ...

    public void setMyService(MyService myService) {
        if (this.myService != null){
           ...
        }
        this.myService = myService;
        if (this.myService != null){
           ...
        }
    }

    ...

    private class MyServiceTrackerCustomizer implements
            ServiceTrackerCustomizer<MyService, MyService> {

        private final BundleContext context;

        public MyServiceTrackerCustomizer(BundleContext context) {
            this.context = context;
        }

        @Override
        public MyService addingService(ServiceReference<MyService> reference) {
            MyService myService = context.getService(reference);
            setMyService(myService);
            return myService;
        }

        @Override
        public void modifiedService(ServiceReference<MyService> reference, MyService service) {
            addingService(reference);
            removedService(reference, service);
        }

        @Override
        public void removedService(ServiceReference<MyService> reference, MyService service) {
            setMyService(null);
            context.ungetService(reference);
        }
    }
}

如果可以使用CDI,还有一个开放的issue