0

私は Equinox OSGi フレームワークで Java アプリケーションを構築しており、DS (宣言型サービス) を使用して、参照および提供されるサービスを宣言しています。これまで実装してきたすべてのサービス コンシューマーはたまたまサービス プロバイダーでもあったため、(1 つのコンシューマーにアタッチするのではなく、複数のコンシューマーが再利用できるように) それらをステートレスにするのは当然のことでした。フレームワークによってインスタンス化されます(デフォルトのコンストラクター、私のコードのどこにも呼び出されません)。

MyClassここで、別の状況があります。サービスを参照するクラスがありますMyServiceが、それ自体はサービス プロバイダーではありません。MyClassOSGi フレームワークにインスタンス化させるのではなく、自分自身をインスタンス化できる必要があります。次に、フレームワークが既存のMyServiceインスタンスをインスタンスに渡すようにしMyClassます。このようなもの:

public class MyClass {

    private String myString;
    private int myInt;

    private MyService myService;

    public MyClass(String myString, int myInt) {
        this.myString = myString;
        this.myInt= myInt;
    }

    // bind
    private void setMyService(MyService myService) {
        this.myService = myService;
    }

    // unbind
    private void unsetMyService(MyService myService) {
        this.myService = null;
    }

    public void doStuff() {
        if (myService != null) {
            myService.doTheStuff();
        } else {
            // Some fallback mechanism
        }
    }

}
public class AnotherClass {

    public void doSomething(String myString, int myInt) {
        MyClass myClass = new MyClass(myString, myInt);

        // At this point I would want the OSGi framework to invoke
        // the setMyService method of myClass with an instance of
        // MyService, if available.

        myClass.doStuff();
    }

}

私の最初の試みは、DS を使用してコンポーネント定義を作成し、そこからMyClass参照することでした。MyService

<scr:component xmlns:scr="http://www.osgi.org/xmlns/scr/v1.1.0" name="My Class">
    <implementation class="my.package.MyClass"/>
    <reference bind="setMyService" cardinality="0..1" interface="my.other.package.MyService" name="MyService" policy="static" unbind="unsetMyService"/>
</scr:component>

ただし、MyClassライフサイクルを管理したくないため、実際にはコンポーネントではありません。インスタンス化を自分で処理したいのです。ニール・バートレットがここで指摘しているように:

たとえば、コンポーネントが特定のサービスに「依存している」と言うことができます。この場合、コンポーネントはそのサービスが利用可能な場合にのみ作成およびアクティブ化され、サービスが利用できなくなると破棄されます。

これは私が望むものではありません。ライフサイクル管理のないバインディングが必要です。[: カーディナリティを0..1(オプションで単項) に設定しても、フレームワークはインスタンス化を試みますMyClass(引数のないコンストラクタがないため失敗します)]

それで、私の質問: DS を使用して、私が探しているこの「バインドのみ、ライフサイクル管理なし」の機能を使用する方法はありますか? DS でこれが不可能な場合、代替手段は何ですか? また、何をお勧めしますか?


更新: 使用ServiceTracker(Neil Bartlett が提案)

重要: 回答として、これの改良版を以下に投稿しました。私はこれを「歴史的」な目的のためにここに置いています。

ServiceTrackerこの場合の申請方法がわかりません。以下に示すように、静的レジストリを使用しますか?

public class Activator implements BundleActivator {

    private ServiceTracker<MyService, MyService> tracker;

    @Override
    public void start(BundleContext bundleContext) throws Exception {
        MyServiceTrackerCustomizer customizer = new MyServiceTrackerCustomizer(bundleContext);
        tracker = new ServiceTracker<MyService, MyService>(bundleContext, MyService.class, customizer);
        tracker.open();
    }

    @Override
    public void stop(BundleContext bundleContext) throws Exception {
        tracker.close();
    }

}
public class MyServiceTrackerCustomizer implements ServiceTrackerCustomizer<MyService, MyService>  {

    private BundleContext bundleContext;

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

    @Override
    public MyService addingService(ServiceReference<MyService> reference) {
        MyService myService = bundleContext.getService(reference);
        MyServiceRegistry.register(myService); // any better suggestion?
        return myService;
    }

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

    @Override
    public void removedService(ServiceReference<MyService> reference, MyService service) {
        bundleContext.ungetService(reference);
        MyServiceRegistry.unregister(service); // any better suggestion?
    }

}
public class MyServiceRegistry {

    // I'm not sure about using a Set here... What if the MyService instances
    // don't have proper equals and hashCode methods? But I need some way to
    // compare services in isActive(MyService). Should I just express this
    // need to implement equals and hashCode in the javadoc of the MyService
    // interface? And if MyService is not defined by me, but is 3rd-party?
    private static Set<MyService> myServices = new HashSet<MyService>();

    public static void register(MyService service) {
        myServices.add(service);
    }

    public static void unregister(MyService service) {
        myServices.remove(service);
    }

    public static MyService getService() {
        // Return whatever service the iterator returns first.
        for (MyService service : myServices) {
            return service;
        }
        return null;
    }

    public static boolean isActive(MyService service) {
        return myServices.contains(service);
    }

}
public class MyClass {

    private String myString;
    private int myInt;

    private MyService myService;

    public MyClass(String myString, int myInt) {
        this.myString = myString;
        this.myInt= myInt;
    }

    public void doStuff() {
        // There's a race condition here: what if the service becomes
        // inactive after I get it?
        MyService myService = getMyService();
        if (myService != null) {
            myService.doTheStuff();
        } else {
            // Some fallback mechanism
        }
    }

    protected MyService getMyService() {
        if (myService != null && !MyServiceRegistry.isActive(myService)) {
            myService = null;
        }
        if (myService == null) {
            myService = MyServiceRegistry.getService();
        }
        return myService;
    }

}

これはあなたがそれを行う方法ですか?そして、上記のコメントで私が書いた質問についてコメントしていただけますか? あれは:

  1. Setサービスの実装が適切に実装されていない場合の問題equalshashCode.
  2. 競合状態:チェックにサービスが非アクティブになる可能性があります。isActive
4

2 に答える 2

0

いいえ、これは DS の範囲外です。自分でクラスを直接インスタンス化する場合は、OSGi API を使用ServiceTrackerしてサービス参照を取得する必要があります。

アップデート:

次の推奨コードを参照してください。明らかに、実際に達成したいことに応じて、これを行うにはさまざまな方法があります。

public interface MyServiceProvider {
    MyService getService();
}

...

public class MyClass {

    private final MyServiceProvider serviceProvider;

    public MyClass(MyServiceProvider serviceProvider) {
        this.serviceProvider = serviceProvider;
    }

    void doStuff() {
        MyService service = serviceProvider.getService();
        if (service != null) {
            // do stuff with service
        }
    }
}

...

public class ExampleActivator implements BundleActivator {

    private MyServiceTracker tracker;

    static class MyServiceTracker extends ServiceTracker<MyService,MyService> implements MyServiceProvider {
        public MyServiceTracker(BundleContext context) {
            super(context, MyService.class, null);
        }
    };

    @Override
    public void start(BundleContext context) throws Exception {
        tracker = new MyServiceTracker(context);
        tracker.open();

        MyClass myClass = new MyClass(tracker);
        // whatever you wanted to do with myClass
    }

    @Override
    public void stop(BundleContext context) throws Exception {
        tracker.close();
    }

}
于 2015-05-29T07:42:46.767 に答える
-1

解決策:使用ServiceTracker(Neil Bartlettの提案による)

注: 反対票の理由を知りたい場合は、 Neil の回答とそのコメントのやり取りを参照してください。

最後に、以下に示すようにServiceTracker、静的レジストリ ( ) を使用して解決しました。MyServiceRegistry

public class Activator implements BundleActivator {

    private ServiceTracker<MyService, MyService> tracker;

    @Override
    public void start(BundleContext bundleContext) throws Exception {
        MyServiceTrackerCustomizer customizer = new MyServiceTrackerCustomizer(bundleContext);
        tracker = new ServiceTracker<MyService, MyService>(bundleContext, MyService.class, customizer);
        tracker.open();
    }

    @Override
    public void stop(BundleContext bundleContext) throws Exception {
        tracker.close();
    }

}
public class MyServiceTrackerCustomizer implements ServiceTrackerCustomizer<MyService, MyService>  {

    private BundleContext bundleContext;

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

    @Override
    public MyService addingService(ServiceReference<MyService> reference) {
        MyService myService = bundleContext.getService(reference);
        MyServiceRegistry.getInstance().register(myService);
        return myService;
    }

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

    @Override
    public void removedService(ServiceReference<MyService> reference, MyService service) {
        bundleContext.ungetService(reference);
        MyServiceRegistry.getInstance().unregister(service);
    }

}
/**
 * A registry for services of type {@code <S>}.
 *
 * @param <S> Type of the services registered in this {@code ServiceRegistry}.<br>
 *            <strong>Important:</strong> implementations of {@code <S>} must implement
 *            {@link #equals(Object)} and {@link #hashCode()}
 */
public interface ServiceRegistry<S> {

    /**
     * Register service {@code service}.<br>
     * If the service is already registered this method has no effect.
     *
     * @param service the service to register
     */
    void register(S service);

    /**
     * Unregister service {@code service}.<br>
     * If the service is not currently registered this method has no effect.
     *
     * @param service the service to unregister
     */
    void unregister(S service);

    /**
     * Get an arbitrary service registered in the registry, or {@code null} if none are available.
     * <p/>
     * <strong>Important:</strong> note that a service may become inactive <i>after</i> it has been retrieved
     * from the registry. To check whether a service is still active, use {@link #isActive(Object)}. Better
     * still, if possible don't store a reference to the service but rather ask for a new one every time you
     * need to use the service. Of course, the service may still become inactive between its retrieval from
     * the registry and its use, but the likelihood of this is reduced and this way we also avoid holding
     * references to inactive services, which would prevent them from being garbage-collected.
     *
     * @return an arbitrary service registered in the registry, or {@code null} if none are available.
     */
    S getService();

    /**
     * Is {@code service} currently active (i.e., running, available for use)?
     * <p/>
     * <strong>Important:</strong> it is recommended <em>not</em> to store references to services, but rather
     * to get a new one from the registry every time the service is needed -- please read more details in
     * {@link #getService()}.
     *
     * @param service the service to check
     * @return {@code true} if {@code service} is currently active; {@code false} otherwise
     */
    boolean isActive(S service);

}
/**
 * Implementation of {@link ServiceRegistry}.
 */
public class ServiceRegistryImpl<S> implements ServiceRegistry<S> {

    /**
     * Services that are currently registered.<br>
     * <strong>Important:</strong> as noted in {@link ServiceRegistry}, implementations of {@code <S>} must
     * implement {@link #equals(Object)} and {@link #hashCode()}; otherwise the {@link Set} will not work
     * properly.
     */
    private Set<S> myServices = new HashSet<S>();

    @Override
    public void register(S service) {
        myServices.add(service);
    }

    @Override
    public void unregister(S service) {
        myServices.remove(service);
    }

    @Override
    public S getService() {
        // Return whatever service the iterator returns first.
        for (S service : myServices) {
            return service;
        }
        return null;
    }

    @Override
    public boolean isActive(S service) {
        return myServices.contains(service);
    }

}
public class MyServiceRegistry extends ServiceRegistryImpl<MyService> {

    private static final MyServiceRegistry instance = new MyServiceRegistry();

    private MyServiceRegistry() {
        // Singleton
    }

    public static MyServiceRegistry getInstance() {
        return instance;
    }

}
public class MyClass {

    private String myString;
    private int myInt;

    public MyClass(String myString, int myInt) {
        this.myString = myString;
        this.myInt= myInt;
    }

    public void doStuff() {
        MyService myService = MyServiceRegistry.getInstance().getService();
        if (myService != null) {
            myService.doTheStuff();
        } else {
            // Some fallback mechanism
        }
    }

}

誰かがこのコードを何らかの目的で使用したい場合は、先に進んでください。

于 2015-06-03T08:00:10.910 に答える