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

相关推荐
遇见火星4 小时前
Jenkins全链路教程——Jenkins调用Maven构建项目
运维·jenkins·maven
Sirius Wu12 小时前
Maven环境如何正确配置
java·maven
:-)20 小时前
idea配置maven国内镜像
java·ide·maven·intellij-idea
敲代码中1 天前
Maven入门到精通
java·maven
甄超锋2 天前
Java Maven更换国内源
java·开发语言·spring boot·spring·spring cloud·tomcat·maven
还是鼠鼠2 天前
tlias智能学习辅助系统--Maven 高级-私服介绍与资源上传下载
java·spring boot·后端·spring·maven
小小工匠3 天前
Maven - Spring Boot 项目打包本地 jar 的 3 种方法
spring boot·maven·jar·system scope
期待のcode3 天前
Maven
java·spring·maven·mybatis
TinpeaV4 天前
(JAVA)自建应用调用企业微信API接口,实现消息推送
java·redis·企业微信·springboot·springflux
是小崔啊4 天前
【Maven】03 - 私服搭建
java·maven