I am trying to set connecting to mongoDB with different profiles.
I have application.yml, application-dev.yml, application-op.yml, application-qa.yml, and application-st.yml. And I want to apply all the properties differently.
For example, I want to apply my MongoDBsource.java class to application.yml
settings.applyConnectionString(
new ConnectionString(String.format("mongodb://%s:%d", host, port)));
But with all the other properties, I want to apply with this code.
settings.applyConnectionString(
new ConnectionString(String.format("mongodb://%s:%d/?replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false", host, port)));
How can I apply this?
I tried @Profile("dev") annotation.
I'd just use property substitutions in the yaml files to achieve this. You could have a mongodb.urlSuffix
which defaults to empty string
application.yaml
mongodb:
host: localhost
port: 5000
urlSuffix: ''
url: mongodb://${mongodb.host}:${mongodb.port}${mongodb.urlSuffix}
application-dev.yaml
mongodb:
urlSuffix: ?replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false
application-op.yaml
mongodb:
urlSuffix: ?replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false
Then
@Component
public class MyFantasticService {
private final MongoSettings settings;
public MyFantasticService(@Value("${mongodb.url}") String mongoUrl) {
settings = new MongoSettings();
settings.applyConnectionString(new ConnectionString(mongoUrl)));
...
}
}