首页 > 解决方案 > 如何在 OSGI 声明式服务中使用 @Property 注释的基数

问题描述

我正在将 Apache Felix SCR 注释迁移到 OSGI 声明式服务 [AEM]。虽然 Migration 我找不到 DS 中基数的确切替代品。

现有的 SCR 实施:

@Component (ds = true, immediate = true, metatype = false, policy = ConfigurationPolicy.OPTIONAL)
@Service (SampleService.class)
public class SampleServiceImpl implements SampleService
{
   private static final int VECTOR = Integer.MIN_VALUE + 1;

    @Property (value = REPOSTING_PATTERN, cardinality = VECTOR,description = "Event reposting pattern for QueuePosting ")
    private static String EVENT_REPOSTING_PATTERN = "eventRepostingPattern";
}

现在它在 OSGi 声明式服务中迁移如下

  @Component (configurationPolicy = ConfigurationPolicy.OPTIONAL, immediate = true, service =SampleService.class,
   property = {SampleServiceImpl .EVENT_REPOSTING_PATTERN +"="+SampleServiceImpl .EVENT_REPOSTING_PATTERN_VALUE })
  public class SampleServiceImpl implements SampleService
   {
     private static String EVENT_REPOSTING_PATTERN = "eventRepostingPattern";
     private static String EVENT_REPOSTING_PATTERN = "eventRepostingPatternValue";
   }

在 DS 注释实现中,我必须如何映射@Property中存在的参数基数。请建议我

标签: javaosgiosgi-bundleapache-felixdeclarative-services

解决方案


关于@Propertyand的文档cardinality像往常一样令人困惑,但我基于假设这些在某种程度上与配置相关。@Designate您可以使用和@ObjectClassDefinition注释为您的服务设置类型安全的配置。该cardinality选项可以在@AttributeDefinition注释中找到。

ExampleServiceimpl.java

import org.osgi.framework.BundleContext;
import org.osgi.service.component.annotations.Activate;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.metatype.annotations.Designate;

@Component( immediate = true, service = ExampleService.class )
@Designate( ocd = ExampleServiceConfig.class )
public class ExampleServiceImpl implements ExampleService {
    
    @Activate
    public void activateService(BundleContext context, ExampleServiceConfig config){
        System.out.println(config.some_config());
    }
}

ExampleServiceConfig.java

import org.osgi.service.metatype.annotations.AttributeDefinition;
import org.osgi.service.metatype.annotations.ObjectClassDefinition;

@ObjectClassDefinition(
    name = " Example service Configuration"
)
public @interface ExampleServiceConfig {
    
    @AttributeDefinition( cardinality = 1 )
    String some_config() default "default value";
}

现在作为免责声明,我自己从未设法使用@AttributeDefinitioncardinality注释过,所以可能会在这里关闭。cardinality当我尝试@AttributeDefinition使用它来查看是否可以使用它来使我的服务配置在 hawtio 中变得漂亮但可能缺少一些步骤时遇到了该选项。

但希望这能为您指明正确的方向。


推荐阅读