我正在尝试获取数据库上的集合列表。我的应用程序使用spring-boot 2.4.1和Azure Cosmos DB。下面是代码块。
String uri= "mongodb://<username>:<password>@<hostname.documents.azure.com>:<port>/?ssl=true";
String dbName= "databaseName";
MongoClient mongoClient = MongoClients.create(uri);
SimpleMongoClientDatabaseFactory mongoDbFactory =
new SimpleMongoClientDatabaseFactory(mongoClient, dbName);
MongoTemplate mongoTemplate = new MongoTemplate(mongoDbFactory);
System.out.println(mongoTemplate.getCollectionNames());
代码抛出一个非常奇怪的StringIndexOutOfBoundsException
。
异常堆栈:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -4
at java.lang.String.substring(String.java:1931)
at com.mongodb.internal.operation.ListCollectionsOperation.projectFromFullNamespaceToCollectionName(ListCollectionsOperation.java:512)
at com.mongodb.internal.operation.ListCollectionsOperation.access$1500(ListCollectionsOperation.java:86)
at com.mongodb.internal.operation.ListCollectionsOperation$ProjectingBatchCursor.next(ListCollectionsOperation.java:418)
at com.mongodb.client.internal.MongoBatchCursorAdapter.next(MongoBatchCursorAdapter.java:64)
at com.mongodb.client.internal.MongoMappingCursor.next(MongoMappingCursor.java:48)
at org.springframework.data.mongodb.core.MongoTemplate.lambda$getCollectionNames$28(MongoTemplate.java:2314)
at org.springframework.data.mongodb.core.MongoTemplate.execute(MongoTemplate.java:535)
at org.springframework.data.mongodb.core.MongoTemplate.getCollectionNames(MongoTemplate.java:2312)
at TestApp.main(TestApp.java:20)
当我连接到一个mongo实例,运行在我的本地与连接字符串"mongodb://localhost:27017"
上面的代码工作正常。
和我的pom.xml
的相关部分
<?xml version="1.0" encoding="UTF-8"?>
<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.4.1</version>
</parent>
<groupId>org.example</groupId>
<artifactId>test-mongo</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
</dependencies>
</project>
对这个错误有什么想法吗?
您确定您的连接uri正确吗?
i can see password part your uri
像这样添加密码部分uri
String uri= "mongodb://<username>:<password>@...