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

Spring Boot application.yaml配置Cassandra端口报错:需为java.lang.integer类型

解决Cassandra Testcontainers配置时application.yaml的Integer类型错误

问题根源

你遇到的错误是因为${spring.cassandra.port}占位符未被正确赋值,Spring解析时空字符串无法转换为Integer类型,导致类型不匹配。

解决方案

1. 给占位符添加默认值兜底

修改application.yaml,给port和contact-points加上默认值,避免变量未注入时出现空值:

spring:
  cassandra:
    contact-points: ${spring.cassandra.contact-points:localhost}
    port: ${spring.cassandra.port:9042}

这样即使Testcontainers的动态变量未生效,也会使用默认的Cassandra端口9042,不会触发类型错误。

2. 通过Testcontainers动态属性源正确注入端口

使用@DynamicPropertySource注解,直接将Testcontainers容器的端口(Integer类型)注入到配置中,确保类型匹配:

import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.testcontainers.containers.CassandraContainer;
import org.testcontainers.junit.jupiter.Container;
import org.testcontainers.junit.jupiter.Testcontainers;
import org.springframework.test.context.DynamicPropertyRegistry;
import org.springframework.test.context.DynamicPropertySource;

@SpringBootTest
@Testcontainers
class CassandraIntegrationTest {

    @Container
    static CassandraContainer<?> cassandraContainer = new CassandraContainer<>("cassandra:latest");

    @DynamicPropertySource
    static void configureCassandraProperties(DynamicPropertyRegistry registry) {
        // 注入contact-points
        registry.add("spring.cassandra.contact-points", cassandraContainer::getContactPoint);
        // 注入端口,getFirstMappedPort()返回Integer类型,直接匹配配置要求
        registry.add("spring.cassandra.port", cassandraContainer::getFirstMappedPort);
    }

    // 你的测试逻辑
    @Test
    void testCassandraConnection() {
        // ...
    }
}

3. 检查配置加载和激活

  • 确保测试类上添加了@ActiveProfiles("test")(如果使用application-test.yaml),避免加载错误的配置文件。
  • 确认配置文件中的占位符名称和动态注入的变量名完全一致(Spring配置大小写不敏感,但严格匹配更稳妥)。

4. 排查版本兼容性

如果使用的是较旧版本的Spring Boot或Testcontainers,升级到稳定版(比如Spring Boot 2.7.x+、Testcontainers 1.17.x+)可以避免一些占位符解析或类型转换的兼容性问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 03:27:47