Migration Solution for Single Elements in OSGI

I work in a Java EE environment in which each application is in its own war file. In WEB-INF / lib of each application war file there is a common bank that is used by all applications. This common jar contains several singletones, which are accessed by many points in the code. Because of the boundaries of war files, each application has its own instances of Singletons. This is how we work today, since we want to configure individual singletones differently in each application.

Now we are moving to the OSGi environment where this solution will no longer work, since each bundle has its own class loader, so if I try to access MySingleton, which is in the "common.jar" bundle from the "appA.jar" package "or from the package" appB.jar "I will get the same instance.

Remember that I "want" another instance of a singleton package. (paradoxically)

Now I understand that the ideal solution would be to fix the code so as not to rely on these singletones, however, due to the limited schedule, I was wondering if you guys can offer some kind of migration solution that would allow me to use bundle- so that each of them could be configured for each package.

+2
source share
3 answers

Your singleton will be a service at OSGi.

Then you need to create a ManagedServiceFactory (see, for example, this article ), responsible for registering different instances of this service; each service will be registered with different properties (fi application = "appA" and application = "appB")

After that, you will get access to the correct service from any application that performs a normal service search by specifying the correct properties.

+2
source

I can come up with several options:

  • Include a copy of all classes in common.jar directly in the WAR bundle.
  • Nest common.jar in each WAR set, then change the bundle class path to MANIFEST.MF to include the nested jar: Bundle-ClassPath:., Common.jar
  • Change singleton to use OSGi services and use ServiceFactory to ensure that each requesting package receives its own instance of this service. You will need to cache the service instance (do not receive / use / disconnect) to avoid getting a new instance with every access.
+1
source

Singleton really belong to services. If the applications (appA, appB) are actually links, then run your service as a ServiceFactory. This will allow you to automatically return a separate instance for each calling packet. This will be easier than ManagedServiceFactory (which requires explicit configuration for each instance) or hacking getters.

+1
source

Source: https://habr.com/ru/post/1308763/


All Articles