Spring Boot项目在IntelliJ IDEA运行正常,终端运行Jar包时MongoDB连接失败问题求助
问题背景
我开发的Spring Boot告警系统在IntelliJ IDEA中启动完全正常,但将项目打包成Jar文件后,在终端运行时抛出了MongoDB连接相关的异常,导致上下文初始化失败。
核心错误日志
ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'alertController': Unsatisfied dependency expressed through field 'alertService'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'alertService': Unsatisfied dependency expressed through field 'alertRepo'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'alertRepository' defined in org.example.repository.AlertRepository defined in @EnableMongoRepositories declared on Application: Cannot resolve reference to bean 'mongoTemplate' while setting bean property 'mongoOperations'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'mongoTemplate' defined in class path resource [org/springframework/boot/autoconfigure/data/mongo/MongoDatabaseFactoryDependentConfiguration.class]: Unsatisfied dependency expressed through method 'mongoTemplate' parameter 0; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'mongoDatabaseFactory' defined in class path resource [org/springframework/boot/autoconfigure/data/mongo/MongoDatabaseFactoryConfiguration.class]: Unsatisfied dependency expressed through method 'mongoDatabaseFactory' parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mongo' defined in class path resource [org/springframework/boot/autoconfigure/mongo/MongoAutoConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.mongodb.client.MongoClient]: Factory method 'mongo' threw exception; nested exception is java.lang.IllegalArgumentException: The connection string is invalid. Connection strings must start with either 'mongodb://' or 'mongodb+srv://
项目配置文件
application.properties
spring.config.import=optional:file:.env[.properties] spring.data.mongodb.uri=${MONGO_DB} spring.data.mongodb.database=${DATABASE_NAME} gmail.email=${GMAIL_ID} gmail.app.password=${GMAIL_APP_PASSWORD}
.env文件(存放环境变量)
MONGO_DB=mongodb+srv://username:password@cluster0.ldofpxl.mongodb.net/?retryWrites=true&w=majority DATABASE_NAME=Master
项目核心代码与依赖
Pom.xml关键部分
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.5.2</version> <!-- Spring Boot版本 --> <relativePath/> </parent> <groupId>org.example</groupId> <artifactId>AlertSystemBE</artifactId> <version>1.0.0-SNAPSHOT</version> <properties> <maven.compiler.source>11</maven.compiler.source> <maven.compiler.target>11</maven.compiler.target> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-mongodb</artifactId> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> </dependency> <!-- 其他依赖如Thymeleaf、邮件、Jsoup等已省略 --> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>
启动类Application.java
package org.example; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; import org.springframework.data.mongodb.repository.config.EnableMongoRepositories; import org.springframework.scheduling.annotation.EnableScheduling; import org.springframework.web.servlet.config.annotation.CorsRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @EnableScheduling @SpringBootApplication @EnableAutoConfiguration @EnableMongoRepositories public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } @Bean public WebMvcConfigurer corsConfigurer() { return new WebMvcConfigurer() { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**") .allowedOrigins("*") .allowedMethods("GET", "PUT", "POST", "PATCH", "DELETE") .maxAge(3600); } }; } }
Repository、Service、Model核心片段
AlertRepository(MongoDB仓库接口):
@Repository public interface AlertRepository extends MongoRepository<Alert, String> { List<Alert> findAllAlertByAssignedTo(int assignedTo); List<Alert> findAllAlertByTimeOfArrivalBetween(Date start, Date end); }
AlertService(业务逻辑层):
@Service public class AlertService { @Autowired private AlertRepository alertRepo; public List<Alert> getAllAlerts() { return alertRepo.findAll(); } public List<Alert> getAlertsByAssignedTo(int assignedTo){ return alertRepo.findAllAlertByAssignedTo(assignedTo); } // 按时间范围查询的方法已省略部分实现 }
Alert(MongoDB文档模型):
@Getter @Setter @AllArgsConstructor @NoArgsConstructor @Document(collection = "Alert") public class Alert { @Id private String id; @NotNull(message = "Title can't be empty") private String title; private String description; private Date timeOfArrival=new Date(); private int assignedTo; // 其他字段已省略 }
已排查的内容
- MANIFEST.MF配置:启动类和Spring Boot相关配置正常,内容如下:
Created-By: Maven Jar Plugin 3.2.0 Build-Jdk-Spec: 11 Implementation-Title: AlertSystemBE Implementation-Version: 1.0.0-SNAPSHOT Main-Class: org.springframework.boot.loader.JarLauncher Start-Class: org.example.Application Spring-Boot-Version: 2.5.2 Spring-Boot-Classes: BOOT-INF/classes/ Spring-Boot-Lib: BOOT-INF/lib/ Spring-Boot-Classpath-Index: BOOT-INF/classpath.idx Spring-Boot-Layers-Index: BOOT-INF/layers.idx
- Java版本:本地安装的是OpenJDK 11,与项目编译版本一致:
PS C:\Users\mansi.keshari\Downloads\demo2\demo2\Alert_Polling> java --version openjdk 11.0.18 2023-01-17 LTS OpenJDK Runtime Environment Corretto-11.0.18.10.1 (build 11.0.18+10-LTS) OpenJDK 64-Bit Server VM Corretto-11.0.18.10.1 (build 11.0.18+10-LTS, mixed mode)
- 打包命令:执行过
mvn clean package和mvn clean install重新打包,Jar文件生成正常。
求助问题
为什么项目在IntelliJ IDEA中能正常读取.env文件里的MongoDB连接字符串,而终端运行Jar包时却提示连接字符串无效?应该如何修复这个问题?
备注:内容来源于stack exchange,提问作者Mansi Keshari

