【问题标题】:How to get the instance of an OSGi service in AEM, without using @Reference annotation?如何在 AEM 中获取 OSGi 服务的实例,而不使用 @Reference 注释?
【发布时间】:2016-03-08 01:07:44
【问题描述】:

我有工厂服务-

com.adobe.test.MyService

我已经在其属性中配置了多个配置。 我想在我的任何课程中使用一个特别配置的服务实例。 我可以使用注释-

@Reference("uniqueId=878")
MyService myService

但是如果我想使用吊索方法呢-

com.adobe.test.MyService myService = sling.getService(com.adobe.test.MyService.class);

我可以在哪里以及如何为我感兴趣的特定实例定义唯一 ID?

【问题讨论】:

    标签: aem sling


    【解决方案1】:

    Object sling 是 SlingSriptHelper 的一个实例,它的方法getServices 接受一个字符串作为第二个参数,代表过滤。

    您可以找到there 的此类过滤示例。您可以在 OSGi 规范中找到过滤器语法的完整规范。

    【讨论】:

      【解决方案2】:

      请试试这个

      static <T> T getService(Class<T> serviceClass) {
          BundleContext bContext = FrameworkUtil.getBundle(serviceClass).getBundleContext();
          ServiceReference sr = bContext.getServiceReference(serviceClass.getName());
              return serviceClass.cast(bContext.getService(sr));
      }
      

      然后就可以调用服务了

      MyService ms = getService(MyService.class);
      

      【讨论】:

      • 你写的代码,基本上和@theanubhava写的代码没什么区别。
      猜你喜欢
      • 1970-01-01
      • 2019-03-11
      • 1970-01-01
      • 2010-11-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-05
      相关资源
      最近更新 更多