如何为 Sling 资源实现自定义 AdapterFactory?

2023-12-27

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

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

要将此语法与您编写和控制的类一起使用,这可以归结为简单地实现适应性强 https://sling.apache.org/documentation/the-sling-engine/adapters.html界面。

但是,如果您想让资源适应您的新自定义类,似乎您必须实现 AdapterFactory 接口并将其注册到 OSGI 中。

这就是如何Adobe 网站 http://dev.day.com/docs/en/cq/5-3/developing/sling-adapters.html#How%20it%20works描述它:

By an 适配器工厂,可以映射任意对象。 这些对象仍然必须实现 Adaptable 接口,并且必须扩展 SlingAdaptable(它将 AdaptTo 调用传递给中央适配器管理器)。这允许挂钩现有类的适应机制,例如资源.

我已经浏览了 SlingScriptAdapterFactory 代码,但最终我并没有在这里连接这些点。基本上我想这样做:

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

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


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

因此,您应该实现 Adaptable 接口,正如您已经描述的那样。然后创建一个正确注释的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);   
    }     
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何为 Sling 资源实现自定义 AdapterFactory? 的相关文章

随机推荐