我想以编程方式创建自定义数据源。这是因为我想在运行时从安全存储中获取密码,而不是在 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/