Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 767
Marsellus Wallace Avatar asked Mar 02 '15 23:03

Marsellus Wallace


People also ask

How do you configure a DataSource in spring boot?

To access the Relational Database by using JdbcTemplate in Spring Boot application, we need to add the Spring Boot Starter JDBC dependency in our build configuration file. Then, if you @Autowired the JdbcTemplate class, Spring Boot automatically connects the Database and sets the Datasource for the JdbcTemplate object.

What is the default DataSource in spring boot?

The primary datasource is autowired by default, and other datasources need to be autowired along with @Qualifier annotation.

How do I configure multiple datasources in spring boot application?

So, to use multiple data sources, we need to declare multiple beans with different mappings within Spring's application context. The configuration for the data sources must look like this: spring: datasource: todos: url: ... username: ...

How many ways are there to define DataSource configuration?

Apache Tomcat provide three ways to configure DataSource in JNDI context.


1 Answers

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(); } 
like image 52
Eddú Meléndez Avatar answered Sep 25 '22 03:09

Eddú Meléndez