264.27. カスタム関数の使用

Camel 2.14.1 以降で利用可能

プロパティー コンポーネントを使用すると、プロパティープレースホルダーの解析中に使用できるサードパーティー関数をプラグインできます。これらの関数は、データベースの検索、カスタム計算の実行など、プレースホルダーを解決するためのカスタムロジックを実行できます。関数の名前は、プレースホルダーで使用される接頭辞になります。これは、以下のコード例で最もよく示されています

<bean id="beerFunction" class="MyBeerFunction"/>

<camelContext xmlns="http://camel.apache.org/schema/blueprint">
  <propertyPlaceholder id="properties">
    <propertiesFunction ref="beerFunction"/>
  </propertyPlaceholder>

  <route>
    <from uri="direct:start"/>
    <to uri="{`{beer:FOO}`}"/>
    <to uri="{`{beer:BAR}`}"/>
  </route>
</camelContext>
注記

camel 2.19.0 から、(propertyPlaceholder タグの) location 属性は必須ではなくなりました

ここでは、カスタム関数を使用するために <propertyPlaceholder> を定義した Camel XML ルートがあります。このカスタム関数は、bean id と呼ばれます (例: beerFunction)。beer 関数は名前として "beer" を使用するため、プレースホルダー構文は、beer:value で開始することにより、beer 関数をトリガーできます。

関数の実装は、以下に示すように 2 つの方法のみです。

public static final class MyBeerFunction implements PropertiesFunction {

    @Override
    public String getName() {
        return "beer";
    }

    @Override
    public String apply(String remainder) {
        return "mock:" + remainder.toLowerCase();
    }
}

関数は org.apache.camel.component.properties.PropertiesFunction インターフェイスを実装する必要があります。getName メソッドは、beer などの関数の名前です。apply メソッドは、実行するカスタムロジックを実装する場所です。サンプルコードは単体テストからのものであるため、モックエンドポイントを参照する値を返すだけです。

Java コードからカスタム関数を登録するには、次のようにします。

PropertiesComponent pc = context.getComponent("properties", PropertiesComponent.class);
pc.addFunction(new MyBeerFunction());