在 Spring Boot 中以编程方式配置 DataSource [英] Configure DataSource programmatically in Spring Boot
问题描述
使用 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
这会创建一个类的数据源:org.apache.tomcat.jdbc.pool.DataSource
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.
推荐答案
如果您使用的是 jdbc
starter,则可以使用 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
就我而言,我的属性以 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屋!