Home > Blockchain >  Spring Boot | spring EL using with annotation attribute value to set any random value using properti
Spring Boot | spring EL using with annotation attribute value to set any random value using properti

Time:12-07

I am using one existing spring boot annotation and want to set the attribute value dynamically using spring expression and want to have one constant value as a prefix,

sample Code snippet

@KafkaListener(topics="${topic.name}", groupId="#{'consumergroup'   (int)(java.lang.Math).random() }")
    public void consumerMethod(){
    
    }

I want to create a new consumer group for each new container using the above kind of implementation.

But I am facing the below exception.

Expression parsing failed; nested exception is org.springframework.expression.spel.SpelParseException: EL1041E: After parsing a valid expression, there is still more data in the expression: 'lparen(()

kindly help me to either use template spring EL or any other way I can use to set dynamic consumer group id with the constant prefix.

CodePudding user response:

groupId="#{'consumergroup'   (100 * T(Math).random()).intValue() }"
  1. There is no cast operator in SpEL. Just because it uses a ConversionService internally to convert from one type to another. I use intValue() any way because the result of random() is Double (not double) - SpEL does coercion into type wrappers for API convenience.
  2. The java.lang is imported into SpEL context automatically. No need to add it for Math type.
  3. 100 *. See Math.random() JavaDocs: it returns the value between 0.0 and 1.0. So, casting to int would always bring you only 0. The casting doesn't do rounding.

Also see Spring Boot configuration properties feature where you can use random value for the groupId:

spring.kafka.consumer.group-id=consumergroup${random.int}

https://docs.spring.io/spring-boot/docs/current/reference/html/features.html#features.external-config.random-values

  • Related