@OSGi中的属性

@OSGi中的属性,osgi,aem,apache-felix,Osgi,Aem,Apache Felix,我正在编写一个服务,并观察到@Property,我们也可以在服务中定义,如下代码所示: @Component(metatype = true, immediate = true, description = "Demo Service to test") @Service(value = DemoService.class) @Properties({ @Property(name = "testprop" , value = "This is Test Property") }

我正在编写一个服务,并观察到@Property,我们也可以在服务中定义,如下代码所示:

@Component(metatype = true, immediate = true, description = "Demo Service to test")
@Service(value = DemoService.class)
@Properties({
        @Property(name = "testprop" , value = "This is Test Property")
})
public class DemoServiceImpl implements DemoService {
     @Property(name = "localprop", value = "Local Value")
    @Activate
    public void activate(ComponentContext ctx)
    {
        String testprop = (String)ctx.getProperties().get("testprop");
        String localprop = (String)ctx.getProperties().get("localprop");
    }
}

这两个属性都显示在felix控制台中&可在我的服务中访问。那么,是什么造成了在组件内部或外部声明它们的差异呢。我看到的一个例子是,我们不能在组件内部使用@Properties。但不确定是什么使它们在功能上彼此不同&什么时候使用它们。

我想你应该谈谈felix注释

您可以在任何方法或成员变量前面使用@Property。但是,这并不意味着将调用方法或设置变量。唯一的好处是,如果您有一个特定的变量,通过在activate方法中赋值来保存属性的值,那么您的类可以根据注释进行更多的自我解释

另一方面,您可以在@properties注释中列出属性。我更喜欢这种方式,因为在本例中,我可以准确地定义属性的顺序,以及它们在生成的元类型xml文件和webconsole中的显示方式

也可能发生这样的情况,即配置属性未分配给任何成员变量,它仅在activate方法中使用。在这种情况下,最好在类前面的@Properties注释中定义它