2017-04-18 7 views
1

AEMでは、文字列の一覧を構成し、複数のサービスに渡って共有する必要があります。これを達成する最良の方法は何ですか?リストは、実行時に構成可能である必要があります。AEMで複数のOSGIサービス間で構成を共有する方法

+0

あなたはこれを見たことがありますか? http://www.nateyolles.com/blog/2015/10/updating-osgi-configurations-in-aem-and-sling OSGI構成を読み込むためのOSGIサービス。 –

答えて

4

構成する専用の構成サービスを作成し、構成された値の1つ以上を必要とする他のすべてのOSGiサービスによって参照される構成サービスを作成できます。

構成例サービス

import org.apache.felix.scr.annotations.Activate; 
import org.apache.felix.scr.annotations.Component; 
import org.apache.felix.scr.annotations.Property; 
import org.apache.felix.scr.annotations.Service; 
import org.apache.sling.commons.osgi.PropertiesUtil; 
import org.osgi.service.component.ComponentContext; 

@Service(ConfigurationService.class) 
@Component(immediate = true, metatype = true) 
public class ConfigurationService { 

    @Property 
    private static final String CONF_VALUE1 = "configuration.value1"; 
    private String value1; 

    @Property 
    private static final String CONF_VALUE2 = "configuration.value2"; 
    private String value2; 

    @Activate 
    public void activate(final ComponentContext componentContext) { 
     this.value1 = PropertiesUtil.toString(componentContext.get(CONF_VALUE1), ""); 
     this.value2 = PropertiesUtil.toString(componentContext.get(CONF_VALUE2), ""); 
    } 

    public String getValue1() { 
     return this.value1; 
    } 

    public String getValue2() { 
     return this.value2; 
    } 
} 

これはそのようなクラスの最低限です。しかし、Apache Felix Configuration Manager(/system/console/configMgr)で設定可能な設定可能なOSGiサービスが作成されます。

注:@Component注釈ではmetatype = trueを使用することが重要です。

次のステップは、このサービスを「消費」サービスで参照することです。

import org.apache.felix.scr.annotations.Activate; 
import org.apache.felix.scr.annotations.Component; 
import org.apache.felix.scr.annotations.Reference; 
import org.apache.felix.scr.annotations.Service; 
import org.osgi.service.component.ComponentContext; 

@Service(MyService.class) 
@Component(immediate = true, metatype = true) 
public class MyService { 

    @Reference 
    private ConfigurationService configurationService; 

    @Activate 
    public void activate(final ComponentContext componentContext) { 
     this.configurationService.getValue1(); 
    } 
} 

注:この例では、AEMとともに使用できるApache SCR注釈を使用しています。あなたは公式ドキュメントでSCRのこの例で使用する注釈(@Service@Component@Property@Reference)についての詳細を学ぶことができます。Apache Felix SCR Annotation Documentation

+0

かなりきちんとした説明。しかし、私たちはここでインターフェイスを使うべきではありませんか?クラス内で実装し、インターフェイスをサービスとして宣言することです。それは十分安全だと思われる。 – theanubhava

+0

@theanubhava私が本文で指摘したように:これは最低限です。明らかにここで改善できることがたくさんあります。簡潔にするために、私は基本原理を実証するための最短の例を選んだ。通常、インタフェースを使用し、 'api'や' impl'バンドルなどで分割します。 – Jens

関連する問題