0

I am working with spring boot. I have properties defined in application.yml.

   spring:
     datasource:
       username: username
       password: password

username and password values are stored externally which program fetches during startup. let's say the bean which fetches them during startup is dbConfig
How can I inject values from dbConfgig to application.yml?

I am using spring-data-jpa autoconfigure which automatically connects to database at startup. I want these values to be loaded to application.yml before spring connects to database.

warrior107
  • 709
  • 1
  • 9
  • 25

3 Answers3

0

I think that first, you must create a thread to detect the change at your db Config file and then may you must re-init your bean (data source) to make your change effect.

See: how-to-reinitialize-a-spring-bean

JMP
  • 4,417
  • 17
  • 30
  • 41
  • reloading bean is something I can work with. But the problem will be during startup the database connection will be made and it will fail. – warrior107 Nov 13 '20 at 09:56
0

There is no need to inject the user/password in application.yml. You can set them programmatically like this:

@Configuration
public class DataSourceConfig {
    
    @Bean
    public DataSource getDataSource() {
        DataSourceBuilder dataSourceBuilder = DataSourceBuilder.create();
        dataSourceBuilder.driverClassName("org.h2.Driver");
        dataSourceBuilder.url("jdbc:h2:mem:test");
        
        // Take the values from external source, then set them
        dataSourceBuilder.username("username");
        dataSourceBuilder.password("password");
        return dataSourceBuilder.build();
    }
}
  • I am using spring-boot-cloud-gcp-sql-autoconfigure. This automatically creates a Datasource bean. It takes the username and password from application.yml – warrior107 Nov 13 '20 at 09:57
  • @warrior107 There is no such thing as `spring-boot-cloud-gcp-sql-autoconfigure`. –  Nov 13 '20 at 12:53
0

You may also try spring cloud to store properties. And you can then use with the help of placeholders.

https://cloud.spring.io/spring-cloud-config/reference/html/

Vipul Pandey
  • 1,507
  • 11
  • 20