Search code examples
javaosgiapache-karaf

Why cant an osgi reference be declared as static datatype?


I am creating an osgi component like this:

@Component (configurationPolicy = ConfigurationPolicy.OPTIONAL, immediate = true)
public class MyServiceAccessor
{
    @Reference (bind = "bindCluster", unbind = "unbindCluster", policy = ReferencePolicy.STATIC, cardinality = ReferenceCardinality.MANDATORY)
    private static Cluster cluster;

I am getting the below message in log:

 395 !ENTRY com.test.eventrecovery 4 0 2021-09-08 10:32:32.559
    396 !MESSAGE [com.test.eventrecovery.MyServiceAccessor(265)] Field cluster in component class com.test.eventrecovery.MyServiceAccessor must not be static

When we were using felix annotations for @Component, @Reference we did not face this issue. I am seeing this when we move to OSGI annotations. Is there any specific reason for this behaviour? Please advise. Also, I am unable to access the official OSGI documentation, which is adding to my woes. :( http://docs.osgi.org/specification/osgi.cmpn/7.0.0/service.component.html - This link doesn't open.


Solution

  • Components instances are objects and thus all references are injected into instance fields. Not static fields. Since there can be multiple instances of a component, allowing injection into static fields would be problematic.

    Try https://docs.osgi.org/specification/osgi.cmpn/7.0.0/service.component.html.