如何为 Sling Resource 实现自定义 AdapterFactory? [英] How to implement a custom AdapterFactory for Sling Resource?

查看:36
本文介绍了如何为 Sling Resource 实现自定义 AdapterFactory?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Adobe AEM 软件提供了几个类,这些类可以采用 apache Sling 资源并将其调整为另一个类,如下所示:

The Adobe AEM software provides several classes which can take an apache Sling Resource and adapt it to another class like so:

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

将此语法与您创作和控制的类一起使用归结为简单地实现 适应性界面.

To use this syntax with classes that you author and control this boils down to simply implementing the Adaptable interface.

然而,如果你想让一个资源适应你的新自定义类,似乎你必须实现 AdapterFactory 接口并在 OSGI 中注册它.

However, if you want to enable a Resource to adaptTo your new custom class, is seems that you have to implement the AdapterFactory interface and register it in OSGI.

这就是 Adobe 网站 对此进行了描述:

This is how the Adobe website describes it:

通过 AdapterFactory,可以映射任意对象.这些对象仍然必须实现 Adaptable 接口,并且必须扩展 SlingAdaptable(它将adapterTo 调用传递给中央适配器管理器).这允许挂钩到现有类(例如 Resource)的 adaptTo 机制.

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 代码,但最终我没有在这里连接点.基本上我想这样做:

I have walked through the SlingScriptAdapterFactory code, but ultimately I am not connecting the dots here. Basically I want to do this:

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

我是否创建了一个实现 AdapterFactory 的类,然后简单地将它与包一起部署,期望 Sling 只能按类型找到它,还是还有更多内容?

Do I create a class that implements AdapterFactory and simply deploy it with the package expecting that Sling will just find it by type or is there more to it?

推荐答案

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

Here is a little bit better documentation https://sling.apache.org/documentation/the-sling-engine/adapters.html

因此您应该实现 Adaptable 接口,正如您已经描述的那样.然后创建一个正确注释的 AdapterFactory:

So you should implement the Adaptable interface, as you already described. Then create a properly annotated 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);   
    }     
}

这篇关于如何为 Sling Resource 实现自定义 AdapterFactory?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆