【问题标题】:Reading an OSGi config value读取 OSGi 配置值
【发布时间】:2014-06-20 17:13:01
【问题描述】:

我有一些类似这样的代码来读取可以使用 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 的模式在哲学上保持一致?

【问题讨论】:

    标签: osgi config sling


    【解决方案1】:

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

    【讨论】:

    • 所以,在字里行间,我猜...可以公平地说,如果我对这种紧密耦合的架构后果感到满意,那么静态方法应该可以工作吗?
    • 好吧,我想说,将(每个实例的)可配置值标记为静态在语义上是错误的——因为它不是。假设将来您可能出于某种原因(例如,在热交换时)想要拥有多个 DummyService 实例,静态变量将导致意外行为。为什么不首先让它保持非静态?
    【解决方案2】:

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

    【讨论】:

    • 我就是这么想的。您能否详细说明可能发生这种情况的情况?重新安装捆绑包时的竞争条件,在激活方法运行之前静态引用可能成功?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-10-24
    • 2015-12-10
    • 1970-01-01
    • 1970-01-01
    • 2016-10-29
    • 2012-03-07
    • 1970-01-01
    相关资源
    最近更新 更多