59.11. Camel XML 配置导入
可从 Camel 2.18 开始
虽然 CDI 优先选择类型为safe 依赖项注入机制,但将现有 Camel XML 配置文件重新调度到 Camel CDI 应用程序中可能会很有用。 在其他用例中,可能需要依赖 Camel XML DSL 来配置其 Camel 上下文。
您可以使用 Camel CDI 在任何 CDI Bean 和 Camel CDI 上提供的 @ImportResource
注释,可以在指定位置自动载入 Camel XML 配置,例如:
@ImportResource("camel-context.xml") class MyBean { }
@ImportResource("camel-context.xml")
class MyBean {
}
Camel CDI 将在类路径的指定位置加载资源(将来可能会添加其他协议)。
从导入的资源的每个 CamelContext
元素和其他 Camel 原语 都会在容器 bootstrap 期间自动部署为 CDI Bean,以便它们从 Camel CDI 提供的自动配置中受益,并在运行时进行注入。如果这样的元素设置了显式 id
属性,则对应的 CDI isan 在 @Named
qualifier 中被授权,例如,给定以下 Camel XML 配置:
<camelContext id="foo"> <endpoint id="bar" uri="seda:inbound"> <property key="queue" value="#queue"/> <property key="concurrentConsumers" value="10"/> </endpoint> <camelContext/>
<camelContext id="foo">
<endpoint id="bar" uri="seda:inbound">
<property key="queue" value="#queue"/>
<property key="concurrentConsumers" value="10"/>
</endpoint>
<camelContext/>
对应的 CDI Bean 会自动部署,并可注入,例如:
@Inject @ContextName("foo") CamelContext context; @Inject @Named("bar") Endpoint endpoint;
@Inject
@ContextName("foo")
CamelContext context;
@Inject
@Named("bar")
Endpoint endpoint;
请注意, CamelContext
Bean 自动使用 @Named
和 @ContextName
限定符。如果导入的 CamelContext
元素没有 id
属性,则使用内置的 @Default
qualifier 部署对应的 bean。
相反,在应用程序中部署的 CDI Bean 可以从 Camel XML 配置中引用(通常使用 ref
属性,如声明以下 Bean):
@Produces @Named("baz") Processor processor = exchange -> exchange.getIn().setHeader("qux", "quux");
@Produces
@Named("baz")
Processor processor = exchange -> exchange.getIn().setHeader("qux", "quux");
可以在导入的 Camel XML 配置中声明该 bean 的引用,例如:
<camelContext id="foo"> <route> <from uri="..."/> <process ref="baz"/> </route> <camelContext/>
<camelContext id="foo">
<route>
<from uri="..."/>
<process ref="baz"/>
</route>
<camelContext/>