我正在编写 OSGI 服务。启动服务后,我收到以下消息。请建议解决此问题。
@Component (service = Service.class, immediate = true)
public class ServiceImpl implements Service{
@Reference (name = "CounterService", policy = ReferencePolicy.DYNAMIC, cardinality = ReferenceCardinality.MANDATORY,
bind = "bindCounter", unbind = "unbindCounter", service = CounterService.class)
public static final AtomicReference<CounterService> myCounterService = new AtomicReference<>();
public void bindCService(CounterService counterService)
{
this.cacheService= cacheService;
}
public void unbindService(CounterService cacheService)
{
this.cacheService= null;
}
}
我在开始服务后收到此消息
-!MESSAGE [com.xxx.xxx.xxx.CounterImpl(29)] 组件类 com.xxx.xxx.xxx.CounterImpl 中的字段 counterService 具有不受支持的类型 java.util.concurrent.atomic.AtomicReference
那么,为什么是 AtomicReference?您也不需要绑定和取消绑定服务。您似乎很困惑:-) 您可能想看看 videos 或 OSGi starter
对于动态情况,这是可行的:
@Component(immediate = true)
public class ServiceImpl implements Service {
@Reference
volatile CounterService myCounterService;
@Activate
void activate() {
...
}
}
如果
CounterService
不是动态的,这是一个非常好的模式:
@Component(immediate = true)
public class ServiceImpl implements Service {
final CounterService myCounterService;
@Activate
public ServiceImpl( @Reference CounterService c ) {
this.myCounterService = c;
}
}
解决此问题的另一种方法是从字段中删除 @Reference 注释并将其添加到绑定方法中。像这样的东西:
@Component (service = Service.class, immediate = true)
public class ServiceImpl implements Service{
public static final AtomicReference<CounterService> myCounterService = new AtomicReference<>();
@Reference (name = "CounterService", policy = ReferencePolicy.DYNAMIC, cardinality = ReferenceCardinality.MANDATORY,
bind = "bindCounterService", unbind = "unbindCounterService", service = CounterService.class)
public void bindCounterService(CounterService counterService)
{
myCounterService = counterService;
}
public void unbindCounterService(CounterService counterService)
{
myCounterService = null;
}
}