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.
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.
The primary datasource is autowired by default, and other datasources need to be autowired along with @Qualifier annotation.
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: ...
Apache Tomcat provide three ways to configure DataSource in JNDI context.
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(); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With