【问题标题】:Adobe AEM/OSGI: How do I access an OSGI service from any class?Adobe AEM/OSGI:如何从任何类访问 OSGI 服务?
【发布时间】:2019-09-02 20:23:25
【问题描述】:

我有一个服务(位于 core/services 内部)和服务实现(位于 core/services/impl)。

我有一个扩展 com.adobe.cq.sightly.WCMUsePojo 的现有类(位于 core/impl/view/components 内)。使用getSlingScripterHelper,这个类可以访问我上面提到的服务。

我正在尝试在不使用 WCMUsePojo 的情况下访问该服务。我该怎么做?

谢谢!

【问题讨论】:

  • 我很好奇,你为什么不想扩展 wcmusepojo?

标签: osgi aem sling


【解决方案1】:

如果您想从 HTL 脚本支持 bean 访问服务,您可以使用 Sling 模型(而不是 WcmUsePojo)并使用 @Inject 注释注入对您的服务的引用。

【讨论】:

    【解决方案2】:

    您可以使用@Reference 从任何其他类调用服务,而无需使用 WCMUsePojo。

    class MyClass
    {
        @Reference
        private MyService myService;
    
        void myMethod()
        {
          myServie.callYourServiceMethod();
        }
    }
    

    【讨论】:

    • 这仅在MyClass 本身是服务/组件时才有效。
    【解决方案3】:

    您可以直接从服务注册中心获取服务-

        final Bundle bundle = FrameworkUtil.getBundle(this.getClass());
        final BundleContext bundleContext = bundle.getBundleContext();
        ServiceReference<MyService> ref = bundleContext.getServiceReference(MyService.class)
        MyService myService = bundleContext.getService(ref);
        // use the service
        bundleContext.ungetService(ref);
    

    【讨论】:

    • 请注意,任何从注册表获取服务的方法都对时间问题高度敏感。在 OSGi 中,可以随时发布和取消发布服务。因此,您总是会遇到 getServiceReference 或 getService 返回 null 的问题。因此,您必须防止 null 并且还必须处理代码流中不存在的服务。通常,将您的代码设置为 DS 组件并通过引用访问服务会更安全。
    猜你喜欢
    • 1970-01-01
    • 2012-07-22
    • 2013-06-14
    • 2014-09-09
    • 1970-01-01
    • 1970-01-01
    • 2011-05-26
    • 2014-01-14
    • 1970-01-01
    相关资源
    最近更新 更多