springmongodbspring-bootmongotemplatemongorepository

Is there a way to update/modify the password of MongoDB connection at runtime?


The ask is to modify the password of a mongodb connection at runtime in a spring boot project. For example let's assume a mongodb connection is established while starting the application with password 'xyz'.I would like to modify the password at runtime by lets say hitting an api. I have tried following solutions so far to tackle this issue:


Solution

  • There is @RefreshScope in Spring Cloud project exactly for your purpose. Here is Spring's documentation about how it works: https://cloud.spring.io/spring-cloud-static/spring-cloud.html#_refresh_scope.

    So all you need to do is update Environment and call org.springframework.cloud.context.scope.refresh.RefreshScope#refresh or org.springframework.cloud.context.scope.refresh.RefreshScope#refreshAll when you need to refresh your context.