Search code examples
javaspringspring-bootdatasource

Configure DataSource programmatically in Spring Boot


With Spring Boot I can instantiate a JdbcTemplate with the following:

Code:

@Autowired
private JdbcTemplate jdbcTemplate;

Properties:

spring.datasource.url=jdbc:postgresql://my_url:my_port/my_other_stuff
spring.datasource.username=my_user_name
spring.datasource.password=my_password
spring.datasource.driver-class-name=org.postgresql.Driver

This create a DataSource of class: org.apache.tomcat.jdbc.pool.DataSource

How do I set the DataSource username/password programmatically?

We have a policy not to store credentials in plain text and I have to use a specific credential provider where I work.


Solution

  • You can use DataSourceBuilder if you are using jdbc starter. Also, in order to override the default autoconfiguration bean you need to mark your bean as a @Primary

    In my case I have properties starting with datasource.postgres prefix.

    E.g

    @ConfigurationProperties(prefix = "datasource.postgres")
    @Bean
    @Primary
    public DataSource dataSource() {
        return DataSourceBuilder
            .create()
            .build();
    }
    

    If it is not feasible for you, then you can use

    @Bean
    @Primary
    public DataSource dataSource() {
        return DataSourceBuilder
            .create()
            .username("")
            .password("")
            .url("")
            .driverClassName("")
            .build();
    }