配置正确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

相关推荐
爱吃南瓜的北瓜11 分钟前
Maven之jjwt依赖爆红
java·pycharm·maven
计算机毕设指导66 小时前
基于SpringBoot的城乡商城协作系统【附源码】
java·spring boot·后端·mysql·spring·tomcat·maven
雪落南城8 小时前
【Maven】maven加载不到包
java·maven
White graces19 小时前
正则表达式效验邮箱格式, 手机号格式, 密码长度
前端·spring boot·spring·正则表达式·java-ee·maven·intellij-idea
LUCIAZZZ1 天前
SkyWalking快速入门
java·后端·spring·spring cloud·微服务·springboot·skywalking
drebander2 天前
Maven 构建中的安全性与合规性检查
java·maven
drebander2 天前
Maven 与 Kubernetes 部署:构建和部署到 Kubernetes 环境中
java·kubernetes·maven
ccmjga2 天前
升级 SpringBoot3 全项目讲解 — Spring Boot 3 中如何发Http请求?
java·spring boot·后端·docker·gradle·springboot·spring security
丁总学Java2 天前
在IDEA的Maven中(同步所有Maven项目)和(重新加载所有Maven项目)的区别
java·maven·intellij-idea
灬Change2 天前
maven 发布本地jar包到私库
linux·maven·jar