在Spring Boot中以编程方式配置DataSource [英] Configure DataSource programmatically in Spring Boot

查看:414
本文介绍了在Spring Boot中以编程方式配置DataSource的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用Spring Boot,我可以使用以下代码实例化 JdbcTemplate

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

代码:

@Autowired
private JdbcTemplate jdbcTemplate;

属性:

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

这创建了一个类的数据源: code> org.apache.tomcat.jdbc.pool.DataSource

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

如何以编程方式设置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.

推荐答案

如果您使用 jdbc 启动器,则可以使用 DataSourceBuilder 。此外,为了覆盖默认的自动配置bean,您需要将bean标记为 @Primary

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

在我的case我的属性以 datasource.postgres 前缀开头。

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

例如

@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();
}

这篇关于在Spring Boot中以编程方式配置DataSource的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆