Joel
Joel

Reputation: 358

Java API's newInstance and OSGi

Is there any case where it is ok to create new factory instances directly in OSGi context? Specifically, what about newInstance() in the Java API?

For example, is it ok to call TransformerFactory.newInstance() or should it be avoided? I think it should be ok, since it is part of the Java API, but the documentation specifies that META-INF/services is used to locate implementations. Does that mean that it doesn't work as expected in combination with OSGi and a third party xml transformer such as Saxon?

What is the proper approach to using XML related factories such as TransformerFactory in OSGi?

Upvotes: 0

Views: 200

Answers (1)

Balazs Zsoldos
Balazs Zsoldos

Reputation: 6046

You should avoid using SPI in OSGi. The classloader of the bundle that contains the Factory class normally does not see the META-INF/services of the bundles that implement the implement the API.

Instead of META-INF/services, the bundle that implements the API should register one or more OSGi services. An adapter bundle that only does the instantiation and the OSGi service registration can be easily written.

You can find examples for SAXParser and SAXParserFactory in the "702 XML Parser Service Specification" of OSGi compendium specification. For TransformerFactory a similar solution should be used.

Update

There are situations when it is not possible to use these factory classes as OSGi services. E.g.: if you use a technology that uses TransformerFactory.

For XML-related APIs I created osgi-xmlcommons-full that

  • contains xml-apis and their implementations
  • overrides the classloading mechanism in the way that implementations are searched within the xmlcommons-full bundle

By using that bundle, there is a greater chance that older technologies that use XML-related factories will work well. To be sure that the XML-related APIs are loaded from this bundle, it is recommended to override org.osgi.framework.system.packages system property in the way that the mentioned packages are excluded.

The bundle is also available on maven-central.

Upvotes: 1

Related Questions