I have a Spring Boot 3.3 application that accesses a MongoDB service. The application is deployed as a Container image to various stages. At some stages, using a username / password to connect to MongoDB is required, while other stages (like my local machine) don't. Changing the MongoDB setup is beyond my scope.
I am trying to address this using Spring's Common Application Properties for MongoDB autoconfiguration.
My application.properties look like this:
spring.data.mongodb.database=${MONGODB_DATABASE:documents}
spring.data.mongodb.host=${MONGODB_HOST:mongodb}
spring.data.mongodb.password=${MONGODB_PASSWORD:}
spring.data.mongodb.port=${MONGODB_PORT:27017}
spring.data.mongodb.username=${MONGODB_USERNAME:}
However, if for environments where MONGODB_PASSWORD
the resulting property line is spring.data.mongodb.password=
and the application refuses to start with:
Caused by: org.springframework.boot.context.properties.bind.BindException: Failed to bind properties under 'spring.data.mongodb.password' to char[]
I tried to make it run using a custom MongoDB client configuration and disabling auto-configuration:
@SpringBootApplication(exclude = {MongoAutoConfiguration.class, MongoDataAutoConfiguration.class})
public class MongoApplication {
public static void main(String[] args) {
SpringApplication.run(MongoApplication .class, args);
}
}
and
@Configuration
public class MongoConfig extends AbstractMongoClientConfiguration {
@Value("${spring.data.mongodb.password:}")
private String password;
[...]
@Override
protected String getDatabaseName() {
return "documents";
}
@Bean
@Override
public MongoClient mongoClient() {
if(this.password == null || this.password.isBlank()) {
return MongoClients.create(
String.formt("mongodb://%s:%d/%s", host, port, database)
);
} else {
return MongoClients.create(
String.formt("mongodb://%s:%s@%s:%d/%s",
username, password, host, port, database)
);
}
}
@Override
protected boolean autoIndexCreation() {
return true;
}
}
This does work for application runtime but integration tests (using Testcontainers) fail, because auto-configuration is required to make @ServiceConnection annotation work.
Looking for hints ..