camel系列-如何调用指定bean重载方法

概述

当 bean 方法存在重载的情况下,组件可能会出现无法判断选择哪个方法的问题,最终系统会抛出异常,导致系统异常,异常的效果如下:Ambiguous method invocations possible

案例解析

如下方法定义,出现了 2 个 sayHello 方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
public class PersonBean {

private String name;

private Integer age;

public PersonBean(String name)
{
this.name=name;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public Integer getAge() {
return age;
}

public void setAge(Integer age) {
this.age = age;
}

public static void sayHello(String name)
{

}

public static void sayHello(String name,Integer age)
{

}
}

DSL 定义

并为指定调用哪个重载方法,那么组件需要根据方法名称和参数类型以及方法参数数量来判断,目前查看源码实现,是没有方法参数数量判断的,所以当入参是 String 的时候,就会同时命中 2 个重载方法,导致系统出现无法选择方法的问题

1
2
3
4
<route>
<from uri="direct:start"/>
<bean method="sayHello" beanType="org.apache.camel.spring.processor.PersonBean"></bean>
</route>

方案

在方法中,明确指定参数数量,参数以表达式的方式来获取,如下示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<routes>
<route>
<from uri="direct:start"/>
<bean method="sayHello(${body})" beanType="org.apache.camel.spring.processor.PersonBean"></bean>
</route>

<route>
<from uri="direct:start"/>
<setHeader name="age">
<constant>2</constant>
</setHeader>
<bean method="sayHello(${body},${header.age})" beanType="org.apache.camel.spring.processor.PersonBean"></bean>
</route>
</routes>