38.3.2. 配置组件
概述 复制链接链接已复制到粘贴板!
您可以通过在 Apache Camel Spring 配置文件 META-INF/spring/camel-context.xml 中配置它来添加组件。要查找组件,组件的 URI 前缀与 Spring 配置中的 bean 元素的 ID 属性匹配。如果组件前缀与 bean 元素 ID 匹配,Apache Camel 将实例化引用的类并注入 Spring 配置中指定的属性。
这种机制优先于自动发现。如果 CamelContext 找到具有必要 ID 的 Spring Bean,则不会尝试使用自动发现来查找组件。
定义组件类的 bean 属性 复制链接链接已复制到粘贴板!
如果有任何要注入到组件类的属性,请将它们定义为 bean 属性。例如:
public class CustomComponent extends
DefaultComponent<CustomExchange> {
...
PropType getProperty() { ... }
void setProperty(PropType v) { ... }
}
getProperty() 方法和 setProperty() 方法访问 属性的值。
在 Spring 中配置组件 复制链接链接已复制到粘贴板!
要在 Spring 中配置组件,请编辑配置文件 META-INF/spring/camel-context.xml,如 例 38.1 “在 Spring 中配置组件” 所示。
例 38.1. 在 Spring 中配置组件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
http://camel.apache.org/schema/spring http://camel.apache.org/schema/spring/camel-spring.xsd">
<camelContext id="camel" xmlns="http://camel.apache.org/schema/spring">
<package>RouteBuilderPackage</package>
</camelContext>
<bean id="component-prefix" class="component-class-name">
<property name="property" value="propertyValue"/>
</bean>
</beans>
ID 组件前缀的 bean 元素配置 component-class-name 组件。您可以使用属性元素将属性注入组件实例中。例如,上例中的 属性 元素将 value 和 attribute Value 注入到属性 中,具体操作为:在组件上调用 setProperty()。
例子 复制链接链接已复制到粘贴板!
例 38.2 “JMS 组件 Spring 配置” 说明如何通过定义 ID 为 jms 的 bean 元素来配置 Apache Camel 的 JMS 组件。这些设置添加到 Spring 配置文件 camel-context.xml 中。
例 38.2. JMS 组件 Spring 配置
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
http://camel.apache.org/schema/spring http://camel.apache.org/schema/spring/camel-spring.xsd">
<camelContext id="camel" xmlns="http://camel.apache.org/schema/spring">
<package>org.apache.camel.example.spring</package>
</camelContext>
<bean id="jms" class="org.apache.camel.component.jms.JmsComponent">
<property name="connectionFactory"
<bean class="org.apache.activemq.ActiveMQConnectionFactory">
<property name="brokerURL"
value="vm://localhost?broker.persistent=false&broker.useJmx=false"/>
</bean>
</property>
</bean>
</beans>
- 1
CamelContext自动实例化在指定的 Java 软件包 org.apache.camel.example.spring 中找到的任何RouteBuilder类。- 2
- ID 为
jms的 bean 元素,配置 JMS 组件。bean ID 对应于组件的 URI 前缀。例如,如果路由指定了 URI 为 的端点,则 Apache Camel 将使用jmsbean 元素中的设置自动加载 JMS 组件。 - 3
- JMS 只是消息传递服务的打包程序。您必须通过在
JmsComponent类上设置connectionFactory属性来指定消息传递系统的 concrete 实施。 - 4
- 在本例中,JMS 消息传递服务的实施是 Apache ActiveMQ。
brokerURL属性初始化与 ActiveMQ 代理实例的连接,其中的消息代理在本地 Java 虚拟机(JVM)中嵌入。如果 JVM 中还没有代理,ActiveMQ 将使用选项broker.persistent=false(代理不会持久消息)和broker.useJmx=false(代理没有打开 JMX 端口)实例化它。