配置正确spring-boot工程启动的时候报错dynamic-datasource Please check the setting of primary

一个两年没有碰的spring-boot工程,启动时报错。因为用了baomidou的多源数据库配置,因此启动时报错primary没有正确配置。经过检查,确定配置文件配置正确。

报错原因是没有读到正确的配置文件。pom文件里的resources标签重定义,把默认的resources文件路径覆盖了。解决方法是,在pom里加一个正确的resources配置,或者把之前的重写的resources删除掉使maven启用默认值。或者是在环境变量里加上spring.config.location,值为配置文件的绝对值。

我是这样定位问题的。

  1. 根据错误日志里的堆栈信息,定位到加载配置的类和函数。

    DynamicDataSourceAutoConfiguration类,dataSourceCreator函数。发现properties里的druid值全部为空。也就是说没有读到配置。

  2. 因为application-local.yml是我用的配置文件,在启动的日志中寻找The following profiles are active: local。发现使用的profile是default。也就是说在applciation.yml文件中的spring.profiles.active: local这一条没有起作用。

  3. 联想到以前同组同事的花活,在IDEA的环境变量里加上spring.active.profiles值设置成local。启动日志里成功地报了The following profiles are active: local。这下能找到application-local.yml了吗?

  4. **不能!**我在Spring core模块的加载配置类中打断点,ConfigFileApplicationListener类的Loader内部类的load方法打断点。发现不会进入到这个函数。

  5. 在IDEA的环境变量里加上spring.config.location值是resources/appplication-local.yml。发现file: application-local.yml文件的resource.exists返回false。也就是说没有这个文件。

    for(Resource resource:resources) {
    if (resource == null || resource.exists()) {...}

  6. what?我又把spring.config.location的值改成classpath:/resources/ 。依然无法读取到。

  7. 把值改成绝对路径,可以正确读取了。

问题解决了。

但是问题是怎么造成的?

这个工程的结构是这样的:

root => root-dependency => app => app-module

发现在root-dependency里有个配置:

复制代码
        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.class</include>
                    <include>**/*.xml</include>
                </includes>
            </resource>
<!--            <resource>-->
<!--                <directory>src/main/resources</directory>-->
<!--                <includes>-->
<!--                    <include>**/*</include>-->
<!--                </includes>-->
<!--            </resource>-->
        </resources>

这个配置项重写了resource,如果没有这个配置,maven默认的effective pom是这样的:

复制代码
<resources>
  <resource>
    <directory>app-module的绝对路径\src\main\resources
    </directory>
  </resource>
</resources>

解决方法有两种,1 删除掉root-dependency里的resource配置。 2. 在app-module里加上src/main/resources配置。

spring boot读取配置文件的过程在这里有详细阐述:

https://www.cnblogs.com/lay2017/p/11484997.html

相关推荐
明月_清风5 小时前
Maven 到底是什么?一篇文章搞懂 Java 项目构建与依赖管理
java·后端·maven
今年下半年14 小时前
SpringBoot整合金蝶中间件
spring boot·中间件·maven
苏渡苇2 天前
Spring Insight 里如何把 Span 画成瀑布时间线
后端·spring·spring cloud·springboot·监控·apm
vx_BS813302 天前
【项目编号:project51629】Spring Boot 乡村自来水缴费系统:把抄表、水费生成与在线缴费做成一条数字化闭环
java·spring boot·eclipse·tomcat·maven
好菇娘の当自强2 天前
【Spring Boot 2.x 与 3.x YAML 配置区别详解】
springboot
cnkeysky2 天前
SpringBoot 整合 nacos 配置中心
nacos·springboot
她说..2 天前
常见设计模式-模板方法模式
java·spring·设计模式·springboot
暮雨哀尘3 天前
JAVA基础练习(四):SpringBoot 实现简易登录功能
java·spring boot·eclipse·maven
小蒜学长3 天前
大学生健康饮食的智慧管理系统(代码+数据库+LW)
java·后端·springboot·大学生·健康饮食
hanchenxing3 天前
CI/CD流水线中的构建缓存:从原理到最小可运行示例CI/CD
maven·构建缓存