在 Camel Context 之外加载环境变量

Load environment variables outside Camel Context

我正在使用 Camel 和蓝图 xml。当我设置 bean 时,我想访问 Camel Context 之外的环境变量。最初我创建了一个环境变量(我正在使用 Windows)

set TEST=test_value

我的蓝图xml是这样的

<?xml version="1.0" encoding="UTF-8"?>

<blueprint  xmlns="http://www.osgi.org/xmlns/blueprint/v1.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.osgi.org/xmlns/blueprint/v1.0.0 
    https://www.osgi.org/xmlns/blueprint/v1.0.0/blueprint.xsd"
    xmlns:cm="http://aries.apache.org/blueprint/xmlns/blueprint-cm/v1.1.0"
    xmlns:cxf="http://camel.apache.org/schema/blueprint/cxf">

    <cm:property-placeholder persistent-id="configuration.file"/>
    ...
    ...
    <bean id="_test" class="com.xxx.Test">
        <argument value="${my.property}"/>
    </bean>
    ...
    <camelContext id="_camelContext"
        xmlns="http://camel.apache.org/schema/blueprint"/>
    ...
    <!-- I can access environment variable with the following 2 ways -->
    <log message="TEST = {{env:TEST}}"/>     
    <log message="TEST via cfg file = {{my.property}}"/>
    ...
    </camelContext> 

还有我的配置文件(在etc文件夹下)configuration.file.cfg

my.property=${env.TEST}

使用之前的方法,我可以访问 bean 中的环境变量(外部上下文)。我怎样才能直接做同样的事情?不使用 属性 文件?

我尝试了以下

<bean id="_test" class="com.xxx.Test">
   <argument value="${env:TEST}"/>
</bean>

但是它不起作用。

谢谢!

请在 https://access.redhat.com/documentation/en-US/Red_Hat_JBoss_Fuse/6.2/html/Apache_Camel_Development_Guide/BasicPrinciples-PropPlaceholders.html 查看。也许这提供了所需的信息。

终于找到方法了。我正在使用 fabric8-karaf-blueprint,它利用 Aries PropertyEvaluator 和来自 fabric8-karaf-core 的 属性 占位符解析器让您解析蓝图 XML 文件中的占位符.

首先在您的 pom.xml 中添加该功能。

<startupFeatures>
  ...
  <feature>fabric8-karaf-blueprint</feature>
  ...
</startupFeatures>

接下来,在我们的 blueprint.xml 中添加命名空间 blueprint-ext。定义不同的前缀和后缀(例如 $[]),以免与现有的 blueprint-cm 混淆。最后使用语法 $[env:TEST] 访问环境变量。接下来是蓝图示例。

<?xml version="1.0" encoding="UTF-8"?>
<blueprint  xmlns="http://www.osgi.org/xmlns/blueprint/v1.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.osgi.org/xmlns/blueprint/v1.0.0 
    https://www.osgi.org/xmlns/blueprint/v1.0.0/blueprint.xsd"
    xmlns:cm="http://aries.apache.org/blueprint/xmlns/blueprint-cm/v1.1.0"
    xmlns:ext="http://aries.apache.org/blueprint/xmlns/blueprint-ext/v1.2.0"
    xmlns:cxf="http://camel.apache.org/schema/blueprint/cxf">

    <cm:property-placeholder persistent-id="configuration.file"/>
    <ext:property-placeholder evaluator="fabric8" placeholder-prefix="$[" placeholder-suffix="]"/>
    ...
    ...
    <bean id="_test" class="com.xxx.Test">
        <argument value="$[env:TEST]"/>
    </bean>