2

I have an OSGi fragment containing non-code resources - that is effectively a jar file containing a set of resources (image files, etc) - that I have built with maven.

I would like to build another bundle with maven which depends on the fragments with the resources. That is, when the code in this bundle is executed, I want the resources from my fragment to be loaded and available with Java's getResources() command.

How can I do this?

1

1 Answer 1

1

If you build with the bnd maven bundle plugin than you can do just do com.example.resource,com.example.images. This will copy the resources from the maven classpath to your own jar. If you have the fragment at some known place, you could also do @resources/fragment.jar. The @ instructs bnd to extract the contents of the given jar and include it in the bundle.

Another solution is to make your bundle not a fragment but a normal bundle and let it register an object. In runtime you get this service and do a getClass().getResource() from it:

 Object resource;

 @Reference(target="resource=myresource")
 void setObject(Object o) {
   this.resource = o;
 }


 void foo() {
       URL u = resource.getClass().getResource();
       ...
 }

The only thing you need to do in the resource bundle is register a service which you can easily do with an activator (the activator must of course reside in this bundle). Alternatively, you can write an extender with the BundleTracker. You put a header in the manifest and when found you register a service that provides the resources. Last, you can of course also find the bundle in the installed set and read the resources from there.

In general, these solutions based on services are much more flexible than the (unfortunately) more well known class loader 'hacks'.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.