[英]How to create Custom DataSource in Spring Boot + Spring Data
我想以編程方式創建Custom DataSource。 這是因為我想在運行時從安全存儲中獲取密碼,而不是在application.yaml中對其進行硬編碼。
我有一個自定義數據源 - myapp.datasource.password,其值為mydb.password.key。 使用ApplicationListener我正在加載機密並使用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作為密碼連接到數據庫,並在啟動時失敗。
我試圖排除數據庫自動配置類
@SpringBootApplication
(exclude={
DataSourceAutoConfiguration.class,
DataSourceTransactionManagerAutoConfiguration.class,
HibernateJpaAutoConfiguration.class
})
但它拋出了這個例外
org.springframework.beans.factory.NoSuchBeanDefinitionException:沒有名為'entityManagerFactory'的bean可用
怎么解決這個? 任何幫助是極大的贊賞!
謝謝
無需排除內置的自動配置。
在你的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();
}
您需要提供Entity Manager Factory bean。 您可以遵循創建名為entityManagerFactory的bean的約定,假設您還沒有。 這里和這里的Spring文檔中有一些例子。
假設你有一個數據源,你可以盡可能少地逃脫:
@Configuration
public class Database {
@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
vendorAdapter.setGenerateDdl(true);
LocalContainerEntityManagerFactoryBean factory =
new LocalContainerEntityManagerFactoryBean();
factory.setJpaVendorAdapter(vendorAdapter);
factory.setPackagesToScan("org.yourcompany.jpaentityroot");
factory.setDataSource(dataSource);
return factory;
}
@Bean
public PlatformTransactionManager transactionManager(EntityManagerFactory emf) {
JpaTransactionManager txManager = new JpaTransactionManager();
txManager.setEntityManagerFactory(emf);
return txManager;
}
@Resource private DataSource dataSource;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.