java - 如何为 Sling Resource 实现自定义 AdapterFactory?

标签 java apache osgi sling aem

Adobe AEM 软件提供了几个类,它们可以采用 apache Sling 资源并将其适应另一个类,如下所示:

Page page = resource.adaptTo(Page.class);

要将此语法与您编写和控制的类一起使用,归结为简单地实现 Adaptable界面。

但是,如果你想让资源适应你的新自定义类,似乎你必须实现 AdapterFactory 接口(interface)并在 OSGI 中注册它。

这就是 Adobe website 的方式描述它:

By an AdapterFactory, which can map arbitrary objects. The objects must still implement the Adaptable interface and must extend SlingAdaptable (which passes the adaptTo call to a central adapter manager). This allows hooks into the adaptTo mechanism for existing classes, such as Resource.

我已经遍历了 SlingScriptAdapterFactory 代码,但最终我并没有将这些点连接起来。基本上我想这样做:

MyClass myClass = Resource.adaptTo(MyClass.class);

我是否创建了一个实现 AdapterFactory 的类,并简单地将它与包一起部署,期望 Sling 会按类型找到它,还是有更多的东西?

最佳答案

这里有一些更好的文档 https://sling.apache.org/documentation/the-sling-engine/adapters.html

所以您应该实现 Adaptable 接口(interface),正如您已经描述的那样。然后创建一个正确注释的 AdapterFactory:

@Component
@Service(value=org.apache.sling.api.adapter.AdapterFactory.class)
@Properties({
   @Property(name = "adaptables", value = { "org.apache.sling.api.resource.Resource" }),
   @Property(name = "adapters", value = { "org.sling.MyClass" })
})
public class MyAdapterFactory implements AdapterFactory{
    public  <AdapterType> AdapterType getAdapter(final Object adaptable, Class<AdapterType> type){
          return new MyClassAdapter(adaptable);   
    }     
}

关于java - 如何为 Sling Resource 实现自定义 AdapterFactory?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17373765/

相关文章:

java - 获取 libGDX And​​roid 游戏的目录文件和类加载器

java - OSGI:如何找出哪些 bundle 订阅了我的服务引用字典中定义的特定属性?

Java - 将CSV解析为ArrayList(需要识别换行符)

java - 如何遍历目录中的文件及其在 Java 中的子目录?

java - JMenuItem重用

apache - 如何配置WAMP apache服务器允许ajax跨域请求?

apache - 复制服务器的 SSL 认证

django - 在 django 中使用 scipy 和 apache 和 mod_wsgi

java - OSGi 的收支平衡点

java - 从 JCA 迁移到 OSGI 是个好主意吗?