读取OSGi配置值

时间:2014-06-20 17:13:02

标签: osgi config sling

我有一些这样的代码来读取可以使用sling:OsgiConfig节点设置的值或者在Felix UI中设置之后...

@Component(immediate = true, metatype = true, label = "Dummy Service")
public class DummyService {
    @Property(label = "Dummy Service Value")
    public static final String DUMMY_VALUE = "dummyValue";
    private static String m_strDummyValue = "default value";

    public static String getDummyValue(){
        return m_strDummyValue;
    }

    @Activate
    protected void activate(ComponentContext context) {
        configure(context.getProperties());
    }

    @Deactivate
    protected void deactivate(ComponentContext context) {
    }

    @Modified
    protected void modified(ComponentContext componentContext) {
        configure(componentContext.getProperties());
    }

    public void updated(Dictionary properties) throws ConfigurationException {
        configure(properties);
    }

    private void configure(Dictionary properties) {
        m_strDummyValue = OsgiUtil.toString(properties.get(DUMMY_VALUE), null);
    }
}

可以在任何消费类中调用

DummyService.getDummyValue();

目前我们的开发环境正在运行。它也非常类似于另一个供应商编写的一些代码,目前正在客户端环境中生产,并且似乎正在运行。但是,我遇到过这篇文章OSGi component configurable via Apache Felix ...建议不要使用像这样的静态访问器。是否存在潜在的问题,其中getDummyValue()可能返回不正确的值,或者建议更多的是与OSGi的模式在哲学上是否一致?

2 个答案:

答案 0 :(得分:1)

一般来说静态不受欢迎,特别是在OSGi中,因为它涉及紧密的代码耦合。最好让DummySerivce成为一个接口,而你的类使用组件作为服务来实现它。然后其他人会参考您组件的服务。一旦注入服务,他们就可以调用服务的方法。

答案 1 :(得分:0)

由于一个主要原因,您不应该这样做:当您访问静态方法时,无法保证已配置DummyService - 与服务引用相比。