Reputation: 483
I am having a datasource configuration class in a Spring boot app. Snippet below
My configuration is fetched from Spring cloud config server. When I change my DB hostname and refresh using /refresh endpoint, the app is NOT using new DB host. ANy idea why ?
@Configuration
@RefreshScope
public classe DBConfig
{
@Resource
private Environment env;
private DataSource ehubDataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(env.getProperty("datasource.driverClassName"));
dataSource
.setUrl(env.getProperty("datasource.url"));
dataSource.setUsername(env.getProperty("datasource.username"));
dataSource.setPassword(env.getProperty("datasource.password"));
return dataSource;
}
}
Upvotes: 3
Views: 6599
Reputation: 868
Normally, the @Configuration class contains beans, which means the datasource method should be marked as @Bean. You need @RefreshScope on each bean.
For a datasource, you probably want @ConfigurationProperties, rather than writing code for each property. @ConfigurationProperties automatically includes @RefreshScope, so you actually don't need RefreshScope here.
With @ConfigurationProperties almost no code is needed.
@Configuration
public class DBConfig
{
@Bean
@ConfigurationProperties("datasource")
public DataSource ehubDataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
return dataSource;
}
}
If your Environment does something other than read the properties files, then this may not work for you.
If you want the bean name to be different from the method name, you can provide a parameter to @Bean. The code below creates the same bean as above.
@Bean(name = "ehubDataSource")
@ConfigurationProperties("datasource")
public DataSource getDataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
return dataSource;
}
Upvotes: 1
Reputation: 3953
As per docs,@RefreshScope will technically work on @Configuration, provided anything that depends on those beans cannot rely on them being updated when a refresh is initiated, unless it is itself in @RefreshScope
So could you please check your "Environment.java", You may forget to specify @RefreshScope in Environment.java. Please share your Environment.java if it is not working.
Upvotes: 3