How to use a derived database name in Spring (Boot) Data MongoDB?

30 Views Asked by At

In a Spring Boot (2.5.x, updating to 3.x is not an option right now) application with externalized (YAML) configuration, I need to have a default/fallback database name in the case where one is not specified in the YAML. The trick is that this default/fallback is derived in Java code (basically, a derivative of the host name with certain characters replaced/removed).

My first thought was to use a SpEL expression to call my method that generates the default name, but I learned that SpEL expressions are not supported in YAML config.

The POJO class where database name ends up is MongoProperties and that's used internally by org.springframework.boot.autoconfigure.data.mongo.MongoDatabaseFactoryConfiguration where it uses the properties to build a @Bean of type MongoDataFactorySupport<?>.

I tried implementing my own @Bean method in my @Configuration class, mimicing what MongoDatabaseFactoryConfiguration does, like this:

@Bean
MongoDatabaseFactorySupport<?> mongoDatabaseFactory(MongoClient mongoClient) {
    return new SimpleMongoClientDatabaseFactory(mongoClient, generateDatabaseName());
}

That doesn't work because at the time my @Configuration class is called, there's no MongoClient bean available. I started down the rabbit hole of also defining my own MongoClient bean, but that turned into a rabbit hole that feels too deep to accomplish something that seems like it should be simple.

Another idea I had is to intercept the populating of MongoProperties and insert my generated value if the provided value is blank. Seems like it should be possible to "override" a POJO @ConfigurationProperties class and do this, but I don't know how.

0

There are 0 best solutions below