0

In Karaf, is there a way for a bundle to read a properties file from another bundle?

I have bundle1, which contains some classes that bundle2 uses (bundle1 exports the package containing those classes in its maven pom via maven-bundle-plugin and bundle2 imports it). But bundle2 also needs to use a properties file from bundle1. Is there a way that in addition to classes, bundle2 can access a file from bundle1?

From what I've read, one option is to deploy the properties to the karaf etc folder via the features file and then it can be accessed from bundle2 via blueprint. I would like to avoid that if possible, as bundle1 is currently not deployed as a feature. So hoping for an alternate approach.

Woodchuck
  • 3,869
  • 2
  • 39
  • 70

1 Answers1

2

The nicest way is to wrap the access through a class of bundle1. Assume bundle1 contains a class named MyClass. Inside this class you can do this.getClass().getResourceAsStream(path). The path is relative to the package of the class.

So a method of this class could return an Inputstream for the properties file or allow access to the actual properties.

In fact you can also access the properties file from bundle2. Simply use MyClass.getResourceAsStream(path) from a class in bundle2. This works as each class is by default loaded by the classloader of the bundle it resides in.

Christian Schneider
  • 19,420
  • 2
  • 39
  • 64
  • Hm, I can access the resource file from the bundle in which it resides (bundle1) using your suggestion (sort of... i.e., I had to change it to ...getClass().getClassLoader()...). However, accessing the file from a different bundle (bundle2) still returns null for me. – Woodchuck Jul 15 '17 at 01:48
  • You need to use a class from bundle1 to get the classloader. Like MyClass.getClass().getClassLoader() where myclass is in bundle1. You can do this from any class in any bundle and will get the classloader of bundle1. – Christian Schneider Jul 15 '17 at 06:57
  • OK, I'll try that again. But it does need to be ...getClass().getClassLoader()..., correct? Just want to clarify, as your answer left off the "getClassLoader()" part. – Woodchuck Jul 15 '17 at 17:44
  • You can use both but the path is then interpreted differently. The getClass().getClassLoader().getResourceAsStream uses an absolute path in the classloader while getClass().getResourceAsStream() is relative to the package if your class. – Christian Schneider Jul 15 '17 at 20:00
  • Ah, thanks much! That really helps clarify. What also helped is I moved my resource file to src/main/resources. I accidentally had it in src/main/java and it wasn't working. Works now! – Woodchuck Jul 16 '17 at 06:19