在 OSGI 的引用对象中调用绑定方法后获取空值

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

在我的项目中,我有一个 OSGI 包。在此包中,我有带有绑定和解除绑定方法的 osgi 引用。当我重新启动我的服务时,首先调用解除绑定方法,将引用对象设置为 null,然后调用绑定方法为引用对象设置值。

我的问题是在使用那个引用对象时,Null.so抛出空指针异常。

我这里做错了什么?

@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();
}

}

虽然 运行 此代码在从另一个 class.

调用 getMetadata() 时出现空指针异常
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)

参见 Bound Service Replacement。使用动态策略时,新服务在绑定方法中注入,然后旧服务在解除绑定方法中删除。所以如果在unbind方法中盲目设置该字段为null,会移除之前注入的服务

经过多次尝试和错误方法,我找到了这个问题的解决方案。 如果将 CacheService cacheService 设置为 static 没有发生空指针异常。

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