You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

@RetryableTopic的attempts属性无法通过SpEL获取topics.size()问题

解决@RetryableTopic中SpEL表达式为attempts赋值不生效的问题

问题原因分析

你的SpEL表达式不生效主要有三个问题:

  • SpEL语法错误:集合大小需要调用size()方法,而非直接访问size属性
  • TestConfig未被Spring容器管理:缺少@Configuration注解,且@ConfigurationPropertis拼写错误
  • 初始化细节:需确保topics列表在SpEL解析前完成初始化

修正后的代码

1. 修正TestConfig类

@Data
@Configuration
@ConfigurationProperties(value = "my.test")
public class TestConfig {

    private SubTest subTest = new SubTest();
    
    public static class SubTest {
        String strTopics = "FIRST, SECOND";
        // 处理逗号前后的空格,避免列表中出现带空格的元素
        List<String> topics = new ArrayList<>(Arrays.asList(strTopics.split("\\s*,\\s*")));
    }
}

2. 修正Test类的@RetryableTopic注解

public class Test {

    private final TestConfig testConfig;

    // 构造函数注入(Spring 4.3+支持自动构造注入)
    public Test(TestConfig testConfig) {
        this.testConfig = testConfig;
    }

    @RetryableTopic(
        attempts = "#{testConfig.subTest.topics.size()}",
        backoff = @Backoff(delay = 1000),
        autoCreateTopics = "false"
    )
    @KafkaListener(topics = "myTopic1")
    public void processMessage(MyPojo1 message) {
       // ... message processing
    }
}

额外注意事项

attempts代表总尝试次数(包含第一次消费),如果你的重试主题数量和尝试次数的逻辑是「重试主题数 = 尝试次数 - 1」,比如2个重试主题对应3次尝试(首次+2次重试),需要调整表达式为:

attempts = "#{testConfig.subTest.topics.size() + 1}"

内容的提问来源于stack exchange,提问作者javaLearnMushigi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.09 12:32:45