小编典典

在Spring Boot中以编程方式配置DataSource

spring

使用Spring Boot,我可以JdbcTemplate使用以下实例化一个:

码:

@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

如何以编程方式设置DataSource用户名/密码?

我们有一项政策,不要以纯文本格式存储凭据,我必须在工作的地方使用特定的凭据提供程序。


阅读 870

收藏
2020-04-12

共1个答案

小编典典

你可以使用DataSourceBuilder,如果你使用的是jdbc首发。另外,为了覆盖默认的自动配置Bean,你需要将Bean标记为@Primary

就我而言,我具有以datasource.postgresprefix 开头的属性。

例如

@ConfigurationProperties(prefix = "datasource.postgres")
@Bean
@Primary
public DataSource dataSource() {
    return DataSourceBuilder
        .create()
        .build();
}

如果对你不可行,则可以使用

@Bean
@Primary
public DataSource dataSource() {
    return DataSourceBuilder
        .create()
        .username("")
        .password("")
        .url("")
        .driverClassName("")
        .build();
}
2020-04-12