Camel在camel-core中提供新的PropertiesComponent,支持开发者在定义Camel Endpoint URI时,使用属性占位符。

这项功能和使用spring的<property-placeholder>标签很相像。然而spring有一个限制,防止第三方框架充分利用spring的属性占位符。

在以下情况使用属性占位符:

1.查找或创建endpoint。

2.到库中查找bean。

3.spring xml提供的附加支持。

4.在camel的属性组件中使用blueprint属性占位符。

语法

使用camel属性占位符的语法是:`file`.`uri`,其中file.uri是属性的key。

可以在url中用属性占位符代表参数值。

属性解析器

通常camel提供可插拔机制允许第三方提供他们自己的解析器来查找属性。当然,他提供解析器的缺省实现:org.apache.camel.component.properties.DefaultPropertiesResolver

这个解析器可以从:文件系统,类路径,osgi库中装载属性,可以用前缀来识别这些属性出处:

▪ ref: Camel 2.4: to lookup in the Registry
▪ file: to load the from file system
▪ classpath: to load from classpath (this is also the default if no prefix is provided)
▪ blueprint: Camel 2.7: to use a specific OSGi blueprint placeholder service

定义位置

PropertiesResolver要知道将要解析的属性所在位置。我们可以定义1-多个位置。可以通过:pc.setLocation("com/mycompany/myprop.properties,com/mycompany/other.properties");定义多个位置,位置之间用逗号分隔。

在camel2.7里,支持使用占位符访问JVM属性和操作系统环境变量。

location=file:${karaf.home}/etc/foo.properties(使用JVM属性)

location=file:${env:APP_HOME}/etc/foo.properties(使用操作系统环境变量)

location=file:${env:APP_HOME}/etc/${prop.name}.properties(使用多个占位符)

在Java DSL中的写法:

创建和注册一个PropertiesComponent:

PropertiesComponent pc = new PropertiesComponent();
pc.setLocation("classpath:com/mycompany/myprop.properties");
context.addComponent("properties", pc);

在spring xml中的配置写法:

与上面Java DSL写法类似的配置方式:

<bean id="properties"
class="org.apache.camel.component.properties.PropertiesComponent">
<property name="location" value="classpath:com/mycompany/myprop.properties"/>
</bean>

另外一种配置方式:

<camelContext ...>
<propertyPlaceholder id="properties" location="com/mycompany/myprop.properties"/>
</camelContext>

使用从OSGI库中查找到的属性:

例如,在OSGI中,我们可以暴露一个服务,该服务的返回值是一个java.util.Properties对象。我们可以通过下面的配置来创建这个Propeties组件:

<propertyPlaceholder id="properties" location="ref:myProperties"/>

这里的myProperties是OSGI库中的服务,也是我们要查找的服务。

使用属性组件的例子:

当在endpoint URIs中使用属性占位符时,可以用properties:组件或者直接在uri中定义占位符。