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/