264.27. 使用自定义功能
从 Camel 2.14.1 开始提供
Properties 组件允许插件第三方功能,它们可在解析属性占位符时使用。然后,这些功能能够执行自定义逻辑来解析占位符,如在数据库中查找、执行自定义计算或不用处。函数的名称变为占位符中使用的前缀。下面是以下示例代码中的最佳描述
<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,location 属性(on propertyPlaceholder tag)不是更多强制的
在这里,我们有一个 Camel XML 路由,它定义了 < ;propertyPlaceholder > 来使用一个自定义功能,我们引用为 bean id - eg the beerFunction。由于 beer 函数使用 "beer" 作为其名称,因此占位符语法可以通过以 beer:value 开始触发 beer 功能。
功能的实现只是两个方法,如下所示:
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 接口。method getName 是函数的名称,如 beer。应用 方法就是我们实施自定义逻辑的位置。因为示例代码来自单元测试,它只是返回一个指向模拟端点的值。
要从 Java 代码注册自定义功能,如下所示:
PropertiesComponent pc = context.getComponent("properties", PropertiesComponent.class);
pc.addFunction(new MyBeerFunction());