javareferenceosgiosgi-bundledeclarative-services

Getting Null value after bind method called in Reference object of OSGI


In my project I have an OSGI bundle. In this bundle I have osgi references with bind and unbind methods .When I restart my service first unbind method is called ,set reference object as null and then bind method is called set value for reference object .

My problem is when in use that reference object ,it is Null.so that null pointer exception is thrown.

What did I do wrong here?

@Component (service = Service.class, immediate = true)
public class ServiceImpl implements Service{

@Reference (name = "CacheService", policy = ReferencePolicy.DYNAMIC, cardinality = 
ReferenceCardinality.MANDATORY, bind = "bindCacheService", unbind = "unbindCacheService")
private CacheService cacheService;

public void bindCacheService(CacheService cacheService)
{     
    this.cacheService= cacheService;
}

public void unbindCacheService(CacheService cacheService)
{     
    this.cacheService= null;
}

public TransformationPojo  getMetadata() throws Exception
{
  
    LOGGER.debug("TransformerIMPL TransformationMetadata getMetadata invoked {}", cacheService);
    TransformationPojo transformationPojo = cacheService.getTransCache();
    return transformationPojo.getMetadata();
}

}

While running this code I got null pointer exception while calling getMetadata() from another class.

2021-06-27T07:35:21.310+0200 | DEBUG | nt-Grouper-Task-10.216.200.229_6 | b.r.e.p.c.u.a.TransformerImpl | transformer.TransformerImpl  100 | 261 - com.common.utils.transformer - 1.30.0.SNAPSHOT | TransformerIMPL TransformationMetadata getMetadata invoked com.common.utils.cacheclient.metadatapojo.TransformationMetadata@765bea96
2021-06-27T07:35:21.310+0200 | DEBUG | nt-Grouper-Task-10.216.200.229_6 | b.r.e.p.c.u.a.TransformerImpl | transformer.TransformerImpl  100 | 261 - com.common.utils.transformer - 1.30.0.SNAPSHOT | TransformerIMPL TransformationMetadata getMetadata invoked null
2021-06-27T07:35:21.311+0200 | ERROR | nt-Grouper-Task-10.216.200.229_6 | .p.c.i.p.g.i.EventGroupingWorker | ice.internal.EventGroupingWorker  162 | 257 - com.common.integration.processors.groupingservice - 1.30.0.SNAPSHOT | Exception in querying the data for grouping. skipping the current query.
java.lang.NullPointerException: null
at com.common.utils.transformer.TransformerImpl.getMetadata(TransformerImpl.java:101)

Solution

  • After several trial and Error methods I got the solution for this Issue. If made CacheService cacheService as static Null pointer Exception didnt occur.

    @Reference (name = "CacheService", policy = ReferencePolicy.DYNAMIC, cardinality = 
    ReferenceCardinality.MANDATORY, bind = "bindCacheService", unbind = "unbindCacheService")
    private static CacheService cacheService;