2013-06-28 35 views
5

Adob​​e的AEM軟件提供了幾類可以採取一個Apache吊帶資源,並使其適應另一個類,像這樣:如何爲Sling資源實現自定義AdapterFactory?

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

要與您創作和控制將此歸結爲簡單的實現類使用此語法Adaptable接口。

但是,如果要啓用資源以適應新的自定義類,似乎必須實現AdapterFactory接口並將其註冊到OSGI中。

這是Adobe website如何描述它:

AdapterFactory,它可以映射任意對象。 對象仍必須實現Adaptable接口,並且必須擴展SlingAdaptable(將adaptTo調用傳遞給中央適配器管理器)。 這允許掛鉤到現有類的adaptTo機制,例如資源

我已經走過SlingScriptAdapterFactory代碼,但最終我沒有在這裏連接點。基本上,我想這樣做:

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

難道我創建一個實現AdapterFactory一類,並簡單地用包期待的是吊帶將只是類型發現或部署它的存在更給它?

回答

4

這裏是一個更好一點的文檔https://sling.apache.org/documentation/the-sling-engine/adapters.html

所以,你應該實現適應性界面,因爲你已經描述。然後創建一個正確註釋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); 
    }  
} 
+0

我能夠驗證這一點,這正是我所需要的。我還沒有理解Apache網站上的評論概述了註冊我的適配器的必要的SCR註釋[https://felix.apache.org/documentation/subprojects/apache-felix-maven-scr-plugin/scr-annotations。 html]現在我只需要弄清楚如何將適配器註釋屬性表示爲適配器支持的類的集合。謝謝! – jedatu

3

請注意,我一直工作在一個更簡單的方法來創建吊帶適配器,通過註釋的方法與新的@Adapter註釋,如

@Component 
    @Service 
    public class C implements AdapterMethodsProvider { 
    @Adapter 
    public CustomerRecord convert(Resource r) { ... } 

    @Adapter 
    public Person adaptToPerson(Resource r) { ... } 
    } 

https://issues.apache.org/jira/browse/SLING-2938瞭解詳細信息,但請注意,即使在Sling樹幹中也沒有,因此它需要一段時間才能在AEM/CQ中發佈和使用。

+0

這會很方便。我會看看。它看起來與Slice的一部分工作是一致的[http://www.cognifide.com/blogs/cq/make-your-cq-life-easier-with-slice/],其目的是使用註釋來映射POJO屬性到Jcr屬性。 – jedatu