Camel技术问题:Simple表达式传Header参数取值报错求非Processor方案
Hey there! Let's break down why your Simple expression is throwing an error and walk through a few ways to fix it without writing a full Processor class.
The Root of the Problem
Your current expression tries to call amqAddressMap.get(header.userTypeID), but here's the key issue:
- An
ArrayList'sget()method expects an int index as its parameter. - If your
userTypeIDheader is a String (or any non-int type), the Simple expression can't resolve the method call correctly—this is almost certainly why you're seeing the "invalid expression" error.
Solution 1: Fix Type Mismatch in Simple Expression
First, ensure the userTypeID header is treated as an integer. If it's stored as a String, you can convert it directly in the Simple expression using a quick type coercion trick:
.setHeader("amqName").simple("${amqAddressMap.get(header.userTypeID * 1)}", String.class)
The * 1 forces the String value to be parsed as an integer. Alternatively, if you control the header's type upstream, make sure userTypeID is set as an Integer instead of a String from the start.
Solution 2: Use OGNL Expression (More Flexible)
Camel supports OGNL expressions, which handle type conversions more gracefully for this kind of lookup. Replace your Simple expression with:
.setHeader("amqName").ognl("amqAddressMap.get(Integer.parseInt(request.headers.get('userTypeID')))")
This explicitly parses the userTypeID header to an integer before passing it to the ArrayList's get() method, avoiding type mismatch issues entirely.
Solution 3: Use a Reusable Bean
If you want cleaner, more maintainable code (especially if you need to add validation or edge-case handling later), create a simple bean to handle the lookup:
- Create the Bean Class:
public class AmqAddressLookup { private final List<String> amqAddressMap; // Inject your ArrayList via constructor public AmqAddressLookup(List<String> amqAddressMap) { this.amqAddressMap = amqAddressMap; } public String getAddress(String userTypeID) { // Add error handling here if needed (e.g., invalid index, non-numeric input) int index = Integer.parseInt(userTypeID); return amqAddressMap.get(index); } }
- Register the Bean in Camel Context:
// Bind the bean to Camel's registry so it's accessible in routes context.getRegistry().bind("amqLookup", new AmqAddressLookup(amqAddressMap));
- Call the Bean in Your Route:
.setHeader("amqName").bean("amqLookup", "getAddress(${header.userTypeID})")
This keeps your route logic clean and centralizes the lookup logic for easy updates down the line.
内容的提问来源于stack exchange,提问作者nidhin

