Tutorial on using Camel in a Web Application

Camel has been designed to work great with the Spring framework; so if you are already a Spring user you can think of Camel as just a framework for adding to your Spring XML files.

So you can follow the usual Spring approach to working with web applications; namely to add the standard Spring hook to load a /WEB-INF/applicationContext.xml file. In that file you can include your usual Camel XML configuration.

Step1: Edit your web.xml

To enable spring add a context loader listener to your /WEB-INF/web.xml file

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"



This will cause Spring to boot up and look for the /WEB-INF/applicationContext.xml file.

Step 2: Create a /WEB-INF/applicationContext.xml file

Now you just need to create your Spring XML file and add your camel routes or configuration.

For example

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"

  <camelContext xmlns="http://camel.apache.org/schema/spring">
      <from uri="seda:foo"/>
      <to uri="mock:results"/>


Then boot up your web application and you're good to go!

Hints and Tips

If you use Maven to build your application your directory tree will look like this...


You should update your Maven pom.xml to enable WAR packaging/naming like this...

	<finalName>[desired WAR file name]</finalName>

To enable more rapid development we highly recommend the jetty:run maven plugin.

Please refer to the help for more information on using jetty:run - but briefly if you add the following to your pom.xml


Then you can run your web application as follows

mvn jetty:run

Then Jetty will also monitor your target/classes directory and your src/main/webapp directory so that if you modify your spring XML, your web.xml or your java code the web application will be restarted, re-creating your Camel routes.

If your unit tests take a while to run, you could miss them out when running your web application via

mvn -Dtest=false jetty:run
  • No labels