【问题标题】:How to wrap long lines of Apache Camel Java DSL code如何包装长行的 Apache Camel Java DSL 代码
【发布时间】:2022-12-18 20:31:20
【问题描述】:

在我的项目中,我们通过 Java DSL 使用 Apache Camel

这是典型路线的外观:

    from("direct:MyPizzaRestaurant")
            .routeId("PizzaRoute")
            .log(LoggingLevel.INFO, LOG, LOG_IN_MESSAGE)
            .bean(veryImportandAndUniqueManagementService, "addTomatoesAndCheeseAndThenPutInTheOven(${in.headers.pizzaContextKey},${in.headers.httpHeaders[pizzaOrderIz]},${in.headers.httpHeaders[restaurantId]},${in.headers.httpHeaders[orderChannel]},${in.headers.customerId},${in.headers.httpHeaders[pizzaType]},${in.headers.httpHeaders[promo]})")
            .end();

现在困扰我的是线长.阅读和维护起来很不舒服,SonarQube 等不同的代码分析工具对此提出了警告。 我想问问你会如何包装这条线,你会推荐什么选项来使这段代码适合 120 个符号宽度

例如你可以这样做:

        from("direct:MyPizzaRestaurant")
                .routeId("PizzaRoute")
                .log(LoggingLevel.INFO, LOG, LOG_IN_MESSAGE)
                .bean(veryImportandAndUniqueManagementService,
                        "addTomatoesAndCheeseAndThenPutInTheOven(
                        "${in.headers.pizzaContextKey}," +
                        "${in.headers.httpHeaders[pizzaOrderIz]}," +
                        "${in.headers.httpHeaders[restaurantId]}," +
                        "${in.headers.httpHeaders[orderChannel]}," +
                        "${in.headers.customerId}," +
                        "${in.headers.httpHeaders[pizzaType]}," +
                        "${in.headers.httpHeaders[promo]})")
                .end();

这样做的缺点是当你使用 Apache Camel Plugin for IntelliJ 时,它允许你使用 Ctrl 单击 with 快速进入方法实现.但它仅在包含方法和输入参数的字符串参数是单行字符串时才有效。因此,在上面的示例中,您将失去快速移动到指定方法的能力,但会获得可读性。有没有办法以某种方式将两者结合起来?

【问题讨论】:

    标签: java apache-camel dsl intellij-plugin code-standards


    【解决方案1】:

    为什么不改用 Camel parameter binding 呢?

    @Bean("veryImportandAndUniqueManagementService")
    public ManagementServiceImpl {
      public Object addTomatoesAndCheeseAndThenPutInTheOven(
               @Header("pizzaContextKey") String ctxKey,
               @Header("custId") Long customerId, 
               etc...
             ) {
    ... 
    }
    

    或者,您也可以定义第二种方法来“解包”Camel 原始消息:

    @Bean("veryImportandAndUniqueManagementService")
    public ManagementServiceImpl {
       public Object addTomatoesAndCheeseAndThenPutInTheOven(Exchange exchange) {
        return this.addTomatoesAndCheeseAndThenPutInTheOven(
         exchange.getMessage().getHeader("pizzaContextKey", String.class),
         exchange.getMessage().getHeader("custId", Long.class), 
         etc...
        );
        }
    }
    

    这样,客户端代码就变得简单多了:

    from("direct:MyPizzaRestaurant")              
       .bean(veryImportandAndUniqueManagementService, "addTomatoesAndCheeseAndThenPutInTheOven")
            
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-05
      • 1970-01-01
      相关资源
      最近更新 更多