About Service Providers

See Also

In version 1.3, the JDK started to use a concept called service providers. This concept introduces a completely declarative style of registration, which is based just on the current classpath of a Java virtual machine and nothing else. This has an important advantage greatly contributing to the ease of use of this registration style: in order to change the set of registered providers, just pick up a JAR file that offers such a provider and include it in application classpath. Immediately its provider will be accessible to all code that searches for it.

The basic idea is that each JAR file (in NetBeans terminology, each module) that wishes to provide an implementation of some interface, for example javax.xml.parsers.DocumentBuilderFactory, can create its own implementation of the interface, say org.sakson.MyFactory, and expose it to the system as a service by creating a META-INF/services/javax.xml.parsers.DocumentBuilderFactory file inside of its own JAR file. The file then contains a name of the implementation class per line. In this example it would contain one line registering the sakson factory: org.sakson.MyFactory.

The DocumentBuilderFactory.newInstance method then searches for all META-INF/services/javax.xml.parsers.DocumentBuilderFactory files by using ClassLoader.getResources("META-INF/services/javax.xml.parsers.DocumentBuilderFactory"), reads their content, and instantiates the class(es) found there by calling their default constructors. The first implementation of the DocumentBuilderFactory is then returned from the newInstance method.

While you can manually create the registration of a service in your module, usually you will use the org.openide.util.lookup.ServiceProvider annotation, which creates such a registration for you automatically.

As already mentioned, this style has been in place since JDK 1.3 and is a standard way to deal with service providers. Not only has NetBeans adopted this style, it is also gaining in popularity among other Java developers. As a result, JDK 1.6 has introduced the new utility class java.util.ServiceLoader.

See Also
About NetBeans Platform and Module Development
About Communicating Between Modules

Legal Notices