Configure DataSource programmatically in Spring Boot Configure DataSource programmatically in Spring Boot java java

Configure DataSource programmatically in Spring Boot


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@Primarypublic DataSource dataSource() {    return DataSourceBuilder        .create()        .build();}

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

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


My project of spring-boot has run normally according to your assistance. The yaml datasource configuration is:

spring:  # (DataSourceAutoConfiguration & DataSourceProperties)  datasource:    name: ds-h2    url: jdbc:h2:D:/work/workspace/fdata;DATABASE_TO_UPPER=false    username: h2    password: h2    driver-class: org.h2.Driver

Custom DataSource

@Configuration@Componentpublic class DataSourceBean {    @ConfigurationProperties(prefix = "spring.datasource")    @Bean    @Primary    public DataSource getDataSource() {        return DataSourceBuilder                .create()//                .url("jdbc:h2:D:/work/workspace/fork/gs-serving-web-content/initial/data/fdata;DATABASE_TO_UPPER=false")//                .username("h2")//                .password("h2")//                .driverClassName("org.h2.Driver")                .build();    }}


All you need to do is annotate a method that returns a DataSource with @Bean.A complete working example follows.

@Beanpublic DataSource dataSource() {    DataSourceBuilder dataSourceBuilder = DataSourceBuilder.create();        dataSourceBuilder.url(dbUrl);        dataSourceBuilder.username(username);        dataSourceBuilder.password(password);        return dataSourceBuilder.build();   }