【问题标题】:spring boot @refreshscope doesn't update datasourcespring boot @refreshscope 不更新数据源
【发布时间】:2017-08-08 07:41:22
【问题描述】:

如果 DB.URL 的环境变量发生变化,我正在尝试更新 DB 数据源。下面是我的课,

@SpringBootApplication
@ConfigurationProperties(value="myapp")
public class MyApp {
@Value("${myapp.db.url}")
String databaseURL;

@Value("${myapp.db.username}")
String databaseUsername;

@Value("${myapp.db.password}")
String databasePassword;

public static void main(String[] args) {
    SpringApplication.run(MyApp.class, args);
}

@Bean
@RefreshScope
@Primary
public DataSource getDataSource() {
    return DataSourceBuilder.create().username(databaseUsername).password(databasePassword).url(databaseURL)
            .driverClassName("org.postgresql.Driver").build();
}
}

但是当我更新环境 DB.URL 时,它不会向新数据库发出请求。

我已经参考了文档,因为它可以更新数据源, http://projects.spring.io/spring-cloud/spring-cloud.html#_refresh_scope

我的课缺少什么?

【问题讨论】:

  • 您可以尝试将其移动到它自己的配置类中,而不是主 Spring Boot 应用程序中吗?您可能还需要配置本身上的RefreshScope
  • 嗨 @DarrenForsythe 如果我使用 @RefreshScope 将数据源配置移动到单独的类。项目无法构建,因为 spring-cloud-config-client 无法检测到数据源。下面是例外,在 org.springframework.boot.actuate.autoconfigure.HealthIndicatorAutoConfiguration$DataSourcesHealthIndicatorConfiguration 的类路径资源 [org/springframework/boot/autoconfigure/jdbc/DataSourceConfiguration$Tomcat.class] 中创建名称为“dataSource”的 bean 时出错。 (HealthIndicatorAutoConfiguration.java:195)
  • 您是否将其与应用程序放在同一个包中?
  • 嗨@DarrenForsythe,是的,我把它放在同一个包里。

标签: java spring spring-mvc spring-boot spring-boot-actuator


【解决方案1】:

您需要将这个 @RefreshScope 注释移动到类上下文 MyApp 上:

@SpringBootApplication
@ConfigurationProperties(value="myapp")
@RefreshScope
public class MyApp {
  ...
}

另外,请确保在服务上请求 POST:http://{your.api.url}/actuator/refresh,以便在更改属性后刷新它。

【讨论】:

    【解决方案2】:

    如果您将 @RefreshScope 添加到类而不从方法中删除。然后 @Value 变量将被刷新。并且数据源会改变。

    【讨论】:

      猜你喜欢
      • 2017-12-21
      • 2017-08-30
      • 1970-01-01
      • 2019-02-12
      • 2023-03-25
      • 2021-10-24
      • 2015-02-21
      • 1970-01-01
      相关资源
      最近更新 更多