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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28821521/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 06:53:00  来源:igfitidea点击:

Configure DataSource programmatically in Spring Boot

javaspringdatasourcespring-bootcredential-providers

提问by Marsellus Wallace

With Spring Boot I can instantiate a JdbcTemplatewith the following:

使用 Spring Boot,我可以JdbcTemplate使用以下内容实例化 a :

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

这将创建一个类的数据源: 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.

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

采纳答案by Eddú Meléndez

You can use DataSourceBuilderif you are using jdbcstarter. Also, in order to override the default autoconfiguration bean you need to mark your bean as a @Primary

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

In my case I have properties starting with datasource.postgresprefix.

在我的情况下,我有以datasource.postgres前缀开头的属性。

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

回答by Rodrigo Villalba Zayas

All you need to do is annotate a method that returns a DataSource with @Bean. A complete working example follows.

您需要做的就是用@Bean 注释一个返回数据源的方法。下面是一个完整的工作示例。

@Bean
public DataSource dataSource() {
    DataSourceBuilder dataSourceBuilder = DataSourceBuilder.create();
        dataSourceBuilder.url(dbUrl);
        dataSourceBuilder.username(username);
        dataSourceBuilder.password(password);
        return dataSourceBuilder.build();   
}

回答by Alfer Wei

My project of spring-boot has run normally according to your assistance. The yaml datasource configuration is:

根据您的帮助,我的spring-boot项目运行正常。yaml 数据源配置为:

spring:
  # (DataSourceAutoConfiguration & DataSourceProperties)
  datasource:
    name: ds-h2
    url: jdbc:h2:D:/work/workspace/fdata;DATABASE_TO_UPPER=false
    username: h2
    password: h2
    driver-class: org.h2.Driver

Custom DataSource

自定义数据源

@Configuration
@Component
public class DataSourceBean {

    @ConfigurationProperties(prefix = "spring.datasource")
    @Bean
    @Primary
    public DataSource getDataSource() {
        return DataSourceBuilder
                .create()
//                .url("jdbc:h2:D:/work/workspace/fork/gs-serving-web-content/initial/data/fdata;DATABASE_TO_UPPER=false")
//                .username("h2")
//                .password("h2")
//                .driverClassName("org.h2.Driver")
                .build();
    }
}

回答by zhuguowei

If you want more datesource configs e.g.

如果你想要更多的日期源配置,例如

spring.datasource.test-while-idle=true 
spring.datasource.time-between-eviction-runs-millis=30000
spring.datasource.validation-query=select 1

you could use below code

你可以使用下面的代码

@Bean
public DataSource dataSource() {
    DataSource dataSource = new DataSource(); // org.apache.tomcat.jdbc.pool.DataSource;
    dataSource.setDriverClassName(driverClassName);
    dataSource.setUrl(url);
    dataSource.setUsername(username);
    dataSource.setPassword(password);
    dataSource.setTestWhileIdle(testWhileIdle);     
    dataSource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMills);
    dataSource.setValidationQuery(validationQuery);
    return dataSource;
}

refer: Spring boot jdbc Connection

参考:Spring 启动 jdbc 连接

回答by MMKarami

As an alternative way you can use DriverManagerDataSource such as:

作为替代方法,您可以使用 DriverManagerDataSource 例如:

public DataSource getDataSource(DBInfo db) {

    DriverManagerDataSource dataSource = new DriverManagerDataSource();

    dataSource.setUsername(db.getUsername());
    dataSource.setPassword(db.getPassword());
    dataSource.setUrl(db.getUrl());
    dataSource.setDriverClassName(db.getDriverClassName());

    return dataSource;
}

However be careful about using it, because:

但是要小心使用它,因为:

NOTE: This class is not an actual connection pool; it does not actually pool Connections. It just serves as simple replacement for a full-blown connection pool, implementing the same standard interface, but creating new Connections on every call. reference

注意:这个类不是一个实际的连接池;它实际上并不池连接。它只是作为成熟连接池的简单替代品,实现相同的标准接口,但在每次调用时创建新的连接。参考

回答by ACV

If you're using latest spring boot (with jdbc starter and Hikari) you'll run into: java.lang.IllegalArgumentException: jdbcUrl is required with driverClassName.To solve this:

如果您使用的是最新的 spring boot(使用 jdbc starter 和 Hikari),您会​​遇到: java.lang.IllegalArgumentException: jdbcUrl is required with driverClassName.要解决这个问题:

  1. In your application.properties:
  1. 在您的 application.properties 中:

datasource.oracle.url=youroracleurl

datasource.oracle.url=youroracleurl

  1. In your application define as bean (@Primaryis mandatory!):
  1. 在您的应用程序中定义为 bean(@Primary是强制性的!):
@Bean
@Primary
@ConfigurationProperties("datasource.oracle")
public DataSourceProperties getDatasourceProperties() {
    return new DataSourceProperties();
}

@Bean
@ConfigurationProperties("datasource.oracle")
public DataSource getDatasource() {
    return getDatasourceProperties().initializeDataSourceBuilder()
           .username("username")
           .password("password")
           .build();
}

回答by Christian Altamirano Ayala

for springboot 2.1.7 working with url seems not to work. change with jdbcUrl instead.

对于使用 url 的 springboot 2.1.7 似乎不起作用。改为使用 jdbcUrl 更改。

In properties:

在属性中:

security:
      datasource:
        jdbcUrl: jdbc:mysql://ip:3306/security
        username: user
        password: pass

In java:

在Java中:

@ConfigurationProperties(prefix = "security.datasource")
@Bean("dataSource")
@Primary
public DataSource dataSource(){

    return DataSourceBuilder
            .create()
            .build();
}

回答by Vladimir

I customized Tomcat DataSourcein Spring-Boot 2.

我在Spring-Boot 2 中自定义了Tomcat DataSource

Dependency versions:

依赖版本:

  • spring-boot: 2.1.9.RELEASE
  • tomcat-jdbc: 9.0.20
  • 弹簧靴:2.1.9.RELEASE
  • tomcat-jdbc:9.0.20

May be it will be useful for somebody.

可能对某人有用。

application.yml

应用程序.yml

spring:
    datasource:
        driver-class-name: org.postgresql.Driver
        type: org.apache.tomcat.jdbc.pool.DataSource
        url: jdbc:postgresql://${spring.datasource.database.host}:${spring.datasource.database.port}/${spring.datasource.database.name}
        database:
            host: localhost
            port: 5432
            name: rostelecom
        username: postgres
        password: postgres
        tomcat:
            validation-query: SELECT 1
            validation-interval: 30000           
            test-on-borrow: true
            remove-abandoned: true
            remove-abandoned-timeout: 480
            test-while-idle: true
            time-between-eviction-runs-millis: 60000
            log-validation-errors: true
            log-abandoned: true

Java

爪哇

@Bean
@Primary
@ConfigurationProperties("spring.datasource.tomcat")
public PoolConfiguration postgresDataSourceProperties() {
    return new PoolProperties();
}

@Bean(name = "primaryDataSource")
@Primary
@Qualifier("primaryDataSource")
@ConfigurationProperties(prefix = "spring.datasource")
public DataSource primaryDataSource() {
    PoolConfiguration properties = postgresDataSourceProperties();
    return new DataSource(properties);
}

The main reason why it had been done is several DataSources in application and one of them it is necessary to mark as a @Primary.

这样做的主要原因是应用程序中有几个 DataSources,其中一个需要标记为@Primary