使用工厂配置将允许您根据不同的配置创建不同的 FooImpl 实例。
例如,在声明式服务中,您可以创建一个类似
的组件
import org.apache.felix.scr.annotations.*;
import org.apache.sling.commons.osgi.PropertiesUtil;
@Component(metatype = true,
name = FooImpl.SERVICE_PID,
configurationFactory = true,
specVersion = "1.1",
policy = ConfigurationPolicy.REQUIRE)
public class FooImpl implements IFoo
{
//The PID can also be defined in interface
public static final String SERVICE_PID = "com.foo.factory";
private static final String DEFAULT_BAR = "yahoo";
@Property
private static final String PROP_BAR = "bar";
@Property(intValue = 0)
static final String PROP_RANKING = "ranking";
private ServiceRegistration reg;
@Activate
public void activate(BundleContext context, Map<String, ?> conf)
throws InvalidSyntaxException
{
Dictionary<String, Object> props = new Hashtable<String, Object>();
props.put("type", PropertiesUtil.toString(config.get(PROP_BAR), DEFAULT_BAR));
props.put(Constants.SERVICE_RANKING,
PropertiesUtil.toInteger(config.get(PROP_RANKING), 0));
reg = context.registerService(IFoo.class.getName(), this, props);
}
@Deactivate
private void deactivate()
{
if (reg != null)
{
reg.unregister();
}
}
}
这里的重点是
- 您使用
configurationFactory 类型的组件
- 在激活方法中,您读取配置,然后根据该配置注册服务
- 在停用时,您明确取消注册服务
- 然后最终用户将创建名为
<pid>-<some name>.cfg 的配置文件。然后 DS 将激活该组件。
然后您可以通过创建名称为<pid>-<some name>.cfg 的配置文件(使用类似文件安装)来创建多个实例@ 类似com.foo.factory-type1.cfg
请参阅JdbcLoginModuleFactory 及其关联的config 以获取此类示例。
如果你想通过普通的 OSGi 实现相同的目标,那么你需要注册一个ManagedServiceFactory。请参阅JaasConfigFactory 获取此类示例。
这里的重点是
- 您使用配置 PID 注册了一个 ManagedServiceFactory 实例作为服务属性
- 在 ManagedServiceFactory(String pid, Dictionary properties) 回调中根据配置属性注册 FooImpl 的实例