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

SpringBoot集成MyBatis主类启动报Hikari缺少jdbcUrl,JUnit正常如何解决

问题根因

测试类可以正常运行是因为@SpringBootTest + @EnableAutoConfiguration会触发Spring Boot的标准配置加载流程:自动加载classpath下的application.properties、自动识别@ConfigurationProperties注解完成数据源参数注入;但你主类启动时仅使用了原生的ClassPathXmlApplicationContext加载XML上下文,没有触发Spring Boot的配置属性绑定逻辑,导致myDataSource Bean创建时所有spring.datasource开头的配置都没有被注入,Hikari参数为空抛出报错。

修复方案

方案1:改用Spring Boot标准启动方式(推荐)

将主类改造为Spring Boot启动类,替换原手动加载XML的逻辑即可,和测试类运行环境完全一致,无需调整其他配置:

@SpringBootApplication
@ImportResource("classpath:/context/smartHome.xml")
public class GatherStatisticsMain {
    private static final Logger LOGGER = LoggerFactory.getLogger(GatherStatisticsMain.class);

    @Autowired
    private HomeAutomation homeAutomation;
    @Autowired
    private StoreDevices storeDevices;

    public void process() throws InterruptedException {
        final DeviceList devices = homeAutomation.getDeviceListInfos();
        storeDevices.process(devices);
    }

    public static void main(String[] args) throws InterruptedException {
        ConfigurableApplicationContext context = SpringApplication.run(GatherStatisticsMain.class, args);
        LOGGER.info("------------" + context.getBeanDefinitionCount());
        GatherStatisticsMain main = context.getBean(GatherStatisticsMain.class);
        main.process();
    }
}

方案2:手动扩展XML上下文的配置处理能力(保留原有启动逻辑)

在/context/smartHome.xml中添加以下配置,手动加载配置文件和启用ConfigurationProperties处理:

<!-- 加载application.properties配置文件 -->
<context:property-placeholder location="classpath:application.properties" />
<!-- 启用@ConfigurationProperties注解处理能力 -->
<bean class="org.springframework.boot.context.properties.EnableConfigurationPropertiesRegistrar"/>

需确认项目依赖中已引入spring-boot-configuration-processor相关依赖。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 04:24:07