【问题标题】:Is there a way to update/modify the password of MongoDB connection at runtime?有没有办法在运行时更新/修改 MongoDB 连接的密码?
【发布时间】:2025-12-28 06:30:14
【问题描述】:

要求是在spring boot项目中在运行时修改mongodb连接的密码。例如,假设在使用密码“xyz”启动应用程序时建立了 mongodb 连接。我想在运行时通过点击 api 来修改密码。 到目前为止,我已尝试以下解决方案来解决此问题:

  • 在运行时替换 mongoTemplate bean:尝试在运行时使用新密码创建一个新的 mongoTemplate Bean,并使用以下link 中给出的方法在上下文中替换它。这种方法的问题是 bean 只刷新一次。理想情况下,每次调用更新密码的 api 时它都应该工作。
  • 在 mongoCredentials 中更新密码: 一种明显的方法是直接在 mongoCredentials 中更新密码,因为 mongoTemplate 使用 mongoCredential 类来存储凭据信息。但问题是 MongoCredentials 类中的密码字段是 'final static' 所以即使有反射我们也不能更新它。尽管有一些技巧可以更新 final 静态字段,但我正在寻找更可接受的解决方案。

【问题讨论】:

    标签: spring mongodb spring-boot mongotemplate mongorepository


    【解决方案1】:

    Spring Cloud 项目中有@RefreshScope 正是为了您的目的。这是 Spring 关于其工作原理的文档:https://cloud.spring.io/spring-cloud-static/spring-cloud.html#_refresh_scope

    因此,您只需更新Environment 并在需要刷新上下文时调用org.springframework.cloud.context.scope.refresh.RefreshScope#refreshorg.springframework.cloud.context.scope.refresh.RefreshScope#refreshAll

    【讨论】:

    • 这是一个很好的解决方案。但在我的具体情况下,我在运行时通过 BeanDefinitionRegistry 生成 mongoTemplate bean,所以我不能直接添加 @RefreshScope 注释。有没有办法用'RefreshScope'注释来注释动态bean?
    • 您应该将 bean 定义的范围值设置为 refresh
    • 我能够创建具有“刷新”范围的 bean。只有一个问题,在 @RefreshScope 的情况下,@Bean 注解的方法在调用 refresh(beanName) 方法后,将在上下文中创建并注册新的 bean 并更新配置。但就我而言,正如我之前所说,我通过 beanRegistry 动态生成 bean。调用 refresh(beanName) 方法后,没有生成新的 bean,即流没有进入 postProcessBeanDefinitionRegistry。有什么想法吗?
    • @RefreshScopeorg.springframework.cloud.context.scope.refresh.RefreshScope 管理,它也是BeanDefinitionRegistryPostProcessor,订单为Ordered.LOWEST_PRECEDENCE - 100。试着让你的后处理器在这个之前运行。现在我只是猜测,但这可能有效
    最近更新 更多