Home > Java, NetBeans, NetBeans Platform, Uncategorized > NetBeans Platform – how to register a class as a provider of multiple services

NetBeans Platform – how to register a class as a provider of multiple services


In NetBeans Platform, there is an annotation called ‘ServiceProvider‘, which allows you to declare that your class provides a certain service (i.e., implements a given interface).   This ties directly into the previously blogged about topic of Lookups, as the class thus annotated is added to the global, default lookup.  Recall that a lookup is a nice wrapper around a Map<Class<E>, Collection<? extends E>>, and allows modules to decouple themselves from the service they request from the actual concrete implementation that they receive.  (A much more in-depth discussion can be found on the Dev FAQ section on lookups).

The issue I ran into is that the documentation is not very clear how you can register your class as providing more than one service (again, implementing more than one interface).  For instance, say I have two interfaces I want a class to fulfill:

public interface Foo {
    public String getFoo();
}

public interface Bar {
    public String getBar();
}

public class FooBar implements Foo, Bar {
    public String getFoo() { return "foo"; }

    public String getBar() { return "bar"; }
}
Since you cannot annotate a class twice, the naive solution fails:
// This is a mistake; you can't declare two annotations like this
@ServiceProvider(service=Foo.class)
@ServiceProvider(service=Bar.class)
public class FooBar implements Foo, Bar {
The correct solution is to use the ServiceProviders annotation, which allows you to provide a list of @ServiceProvider declarations.
@ServiceProviders(value={
    @ServiceProvider(service=Foo.class),
    @ServiceProvider(service=Bar.class)}
)
Now you can find the FooBar instance via either defined interface.
  1. Dave
    February 3, 2011 at 7:13 am

    Thanks!

  2. February 25, 2014 at 4:12 am

    Thanks !!

  3. d3ric
    October 19, 2016 at 1:25 am

    Doesn’t work with NetBeans 8.1 😦 Any other solutions?

    • d3ric
      October 19, 2016 at 1:29 am

      sorry, I’ve overlooked the plural in first annotations. “@ServiceProviders” works fine.

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: