@RefreshScope 没有按预期工作 - SpringBoot

@RefreshScope is not working as expected- SpringBoot

我已经在 Spring 引导应用程序的 @RefreshScope 中配置了一个 bean,并覆盖了数据源配置,如下所示:

@Configuration
public class DataSourceConfig {

@Autowired
private DbConfig dbConfig;

@Bean
@Primary
@RefreshScope
public DataSource dataSource() {
    HikariDataSource dataSource=new HikariDataSource();
    dataSource.setJdbcUrl("jdbc:h2:file:~/spring-boot-h2-db");
    dataSource.setUsername(dbConfig.getUsername());        
    dataSource.setMaximumPoolSize(dbConfig.getMaxPoolSize());
    dataSource.setPassword("");
    dataSource.setDriverClassName("org.h2.Driver");
    return dataSource;
  }
}

和 DbConfig:

@PropertySource("file:/Users/rarifi/temp/application.properties")
@RefreshScope
@Component
@ConfigurationProperties(
    prefix = "spring.datasource"
)
public class DbConfig {

@Value("username")
private String username;

private int maxPoolSize;

public int getMaxPoolSize() {
    return maxPoolSize;
}

public void setMaxPoolSize(int maxPoolSize) {
    this.maxPoolSize = maxPoolSize;
}

@Autowired
private StandardEnvironment environment;

public void setUsername(String username) {
    this.username = username;
}

public String getUsername() {
    return username;
  }
}

我在另一段代码中更新配置 属性 文件后调用 refreshEndpoint.refresh。在刷新期间,代码进入 getDatasource 但仍指向初始化期间使用的相同属性。需要更改什么才能读取更改的属性?如果属性未定义为@RefreshScope

,则在运行时更新属性

您需要在 class 上下文中移动 @RefreshScope 注释。

@Configuration
@RefreshScope

public class DataSourceConfig {
  ....
}

我终于找到问题所在了。它与 @RefreshScope 注释无关,但与重新加载属性的方式有关。我将 @PropertySource 从 @PropertySource("file:/Users/rarifi/temp/application.properties") 更改为 @PropertySource("classpath:/application.properties") 并且它开始正常工作。当我将 spring.config.location 中的位置设置为环境变量时,当 运行 应用程序

时,它也有效