有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何设置apache camel groovy脚本组件的属性

我正在使用ApacheCamel脚本组件调用外部groovy文件

     from("activemq:queue:test.ChooseIManger")
     .script().groovy("resource:classpath:tests/port/test.gsh")

我想在调用此脚本时传递一些属性。 我可以用如下简单的java代码来实现这一点

        Binding binding = new Binding();
        binding.setProperty("INPUTS", inputs);
        binding.setProperty("RESULT", results);

        GroovyShell shell = new GroovyShell(binding); 
        Object script = shell.evaluate(getScript("tests/port/test.gsh"));

但是,我们如何像这样在camel路由器中绑定属性

塔克斯


共 (2) 个答案

  1. # 1 楼答案

    根据documentation,似乎应该能够通过使用自定义GroovyShellFactory来重载默认Groovy实例

    根据您提供的信息:

    public class CustomGroovyShellFactory implements GroovyShellFactory {
    
      public GroovyShell createGroovyShell(Exchange exchange) {
        Binding binding = new Binding();
        binding.setProperty("INPUTS", inputs);
        binding.setProperty("RESULT", results);
        return new GroovyShell(binding);
      }
    }
    

    然后将该bean添加到您的上下文中

  2. # 2 楼答案

    这在Camel中可能不可能实现。在类org.apache.camel.language.groovy.GroovyExpression的方法evaluate中,所有以前设置的绑定都被骆驼绑定(例如camelContext)覆盖,而不是合并

    public <T> T evaluate(Exchange exchange, Class<T> type) {
        Script script = instantiateScript(exchange);
        script.setBinding(createBinding(exchange));
        Object value = script.run();
    
        return exchange.getContext().getTypeConverter().convertTo(type, value);
    }
    

    因此,所有绑定都将丢失。如果不改变骆驼本身,我想这是无法解决的

    但是,如果有人能解决这个问题,我真的很想知道