OSGi如何运行一项服务的多个实例 [英] OSGi how to run mutliple instances of one service
问题描述
是否可以在osgi框架中运行同一服务的多个实例? 更具体地说,我需要启动一个服务的多个实例,但是每个实例应接收不同的参数.这是因为服务具有相似的功能.但是,我不想为每个变体编写服务,而是要重用一个实现类.
Is it possible to run multiple instance of the same service in the osgi framework? More specific, I need to start multiple instances of a service, but each instance should recieve different parameters. This is because the services have similar functionality. But instead of writing a service for every variation, I want to reuse one implementing class.
我已经在框架api中找到了registerService方法.
I've already found the registerService method in the framework api.
ServiceRegistration<?> registration = bundlecontext.registerService(
className, class, null);
但是,我似乎只为每个类创建一个实例.有解决方法吗?
however, i seem to create only one instance of each class. Is there a workaround for this?
最好是类似
ServiceRegistration<?> registration = bundlecontext.registerService(
className + "#" + (++counter), new classInstance(), null);
推荐答案
请注意,将声明式服务与相应的注释配合使用非常容易,这是Apache Sling代码库的摘录(
Note that using Declarative Services with the corresponding annotations makes this quite easy, here's an excerpt from the Apache Sling codebase (ConfiguredFeature.java):
@Component(
name = "org.apache.sling.featureflags.Feature",
metatype = true,
configurationFactory = true,
policy = ConfigurationPolicy.REQUIRE)
@Service
public class ConfiguredFeature implements Feature {
@Property(label = "Name", description = "Short name of this feature")
private static final String NAME = "name";
private String name;
@Activate
private void activate(final Map<String, Object> configuration) {
this.name = PropertiesUtil.toString(configuration.get(NAME), "");
}
...
}
使用configurationFactory = true
和policy = ConfigurationPolicy.REQUIRE
会为每个对应的OSGi配置创建此服务的一个实例,这是创建多个实例的自然方法.
Using configurationFactory = true
and policy = ConfigurationPolicy.REQUIRE
causes one instance of this service to be created for each corresponding OSGi configuration, which is a natural way of creating multiple instances.
这篇关于OSGi如何运行一项服务的多个实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!