在运行时以编程方式定义和删除Spring Boot / Spring JPA数据源?

时间:2017-01-27 03:42:50

标签: java spring spring-boot spring-data spring-data-jpa

我需要在运行时动态创建Spring Boot数据源。有人知道怎么做吗。实际上,我需要按需执行此操作:

spring:
  datasource:
    url: jdbc:h2:mem:testdb1;
    username: sa
    password:
    driver-class-name: org.h2.Driver
    platform: h2

spring:
  datasource:
    url: jdbc:h2:mem:testdb2;
    username: sa
    password:
    driver-class-name: org.h2.Driver
    platform: h2

...

spring:
  datasource:
    url: jdbc:h2:mem:testdbN;
    username: sa
    password:
    driver-class-name: org.h2.Driver
    platform: h2

思想?

1 个答案:

答案 0 :(得分:2)

尝试以下方式以编程方式创建数据源

DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setUrl("jdbc:h2:mem:testdb1");
dataSource.setUsername("sa");
dataSource.setPassword("");
dataSource.setDriverClassName("org.h2.Driver");