第 6 章 在 Spring XML 中使用 Camel
将 Camel 与 Spring XML 文件一起使用是一种在 Camel 中使用 XML DSL 的方法。Camel 过去一直使用 Spring XML 进行很长时间。Spring 框架以 XML 文件开头,作为构建 Spring 应用程序的常见配置。
Spring 应用程序示例
<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.xsd http://camel.apache.org/schema/spring http://camel.apache.org/schema/spring/camel-spring.xsd "> <camelContext xmlns="http://camel.apache.org/schema/spring"> <route> <from uri="direct:a"/> <choice> <when> <xpath>$foo = 'bar'</xpath> <to uri="direct:b"/> </when> <when> <xpath>$foo = 'cheese'</xpath> <to uri="direct:c"/> </when> <otherwise> <to uri="direct:d"/> </otherwise> </choice> </route> </camelContext> </beans>
<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.xsd
http://camel.apache.org/schema/spring http://camel.apache.org/schema/spring/camel-spring.xsd
">
<camelContext xmlns="http://camel.apache.org/schema/spring">
<route>
<from uri="direct:a"/>
<choice>
<when>
<xpath>$foo = 'bar'</xpath>
<to uri="direct:b"/>
</when>
<when>
<xpath>$foo = 'cheese'</xpath>
<to uri="direct:c"/>
</when>
<otherwise>
<to uri="direct:d"/>
</otherwise>
</choice>
</route>
</camelContext>
</beans>
6.1. 在 Spring XML 文件中使用 Java DSL
您可以使用 Java Code 定义 RouteBuilder 实现。它们在 spring 中定义为 Bean,然后在您的 camel 上下文中引用,如下所示:
<camelContext xmlns="http://camel.apache.org/schema/spring"> <routeBuilder ref="myBuilder"/> </camelContext> <bean id="myBuilder" class="org.apache.camel.spring.example.test1.MyRouteBuilder"/>
<camelContext xmlns="http://camel.apache.org/schema/spring">
<routeBuilder ref="myBuilder"/>
</camelContext>
<bean id="myBuilder" class="org.apache.camel.spring.example.test1.MyRouteBuilder"/>
6.1.1. 配置 Spring Boot 应用程序
要将 Spring Boot Autoconfigure XML 路由用于 Bean,您需要修改导入 XML 资源。为此,您可以使用 Configuration
类。
例如,如果 Spring XML 文件位于 src/main/resources/camel-context.xml
中,您可以使用以下配置类来加载 camel-context :
示例:使用 配置
类
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.ImportResource; /** * A Configuration class that import the Spring XML resource */ @Configuration // load the spring xml file from classpath @ImportResource("classpath:camel-context.xml") public class CamelSpringXMLConfiguration { }
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource;
/**
* A Configuration class that import the Spring XML resource
*/
@Configuration
// load the spring xml file from classpath
@ImportResource("classpath:camel-context.xml")
public class CamelSpringXMLConfiguration {
}
提示
如需示例应用程序,请参阅 camel-spring-boot-examples 存储库中的 XML 导入 示例。