java - 如何在 Spring Boot + Spring Data 中创建自定义数据源

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

我想以编程方式创建自定义数据源。这是因为我想在运行时从安全存储中获取密码,而不是在 application.yaml 中对其进行硬编码。

我有一个自定义数据源 - myapp.datasource.password,其值为 mydb.password.key。使用 ApplicationListener 我正在加载 secret 并使用 mydb.password.key 作为键设置 myapp.datasource.password 的值。

myapp:
     datasource:
        driverClassName: com.mysql.cj.jdbc.Driver
        url: jdbc:mysql://localhost:3306/mydb?autoReconnect=true&characterEncoding=utf8
        username: myuser
        password: mydb.password.key

现在,HibernateJpaAutoConfiguration 正在尝试使用 mydb.password.key 作为密码连接到 DB,但在启动时失败了。

我试图排除数据库自动配置类

@SpringBootApplication
    (exclude={
    DataSourceAutoConfiguration.class,
    DataSourceTransactionManagerAutoConfiguration.class,
    HibernateJpaAutoConfiguration.class
    })

但是它抛出这个异常

org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'entityManagerFactory' available

如何解决?非常感谢任何帮助!

谢谢

最佳答案

无需排除内置的自动配置。

在你的 application.yml 中

myapp:
     datasource:
        driverClassName: com.mysql.cj.jdbc.Driver
        url: jdbc:mysql://localhost:3306/mydb?autoReconnect=true&characterEncoding=utf8
        username: myuser
        # make sure you exclude password from here

在你的配置中:

// all the other datasource properties will be applied from "myapp.datasource" except password because you excluded it
@ConfigurationProperties(prefix = "myapp.datasource")
@Bean
@Primary // this will override the datasource autoconfiguration and use your own everywhere
public DataSource dataSource() {
    String password = retrieveMyPasswordSecurely();

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

关于java - 如何在 Spring Boot + Spring Data 中创建自定义数据源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45852508/

相关文章:

java - org.hibernate.session 准备好的声明

java - Spring Boot 管理 - 基本身份验证

java - 计算Java的 future 投资额

java - Java中的字符串...参数

java - 对Integer对象进行加操作,从目录中读取多个文件以在Java中创建词袋

spring - 为什么我尝试使用 Spring Data JPA 执行记录插入时会出现此错误?表 'db_test.hibernate_sequence' 不存在

java - 如何设置@OneToOne映射的约束名称?

spring-boot - 在 jar 外的 html 中定位图像

java - 初始化受 Spring 身份验证保护的存储库

java.lang.ClassCastException : android. widget.ImageButton 无法转换为 android.widget.TextView