2017-08-24 10 views
1

プログラムでカスタムDataSourceを作成したいと思います。これは、application.yamlでハードコードするのではなく、実行時に安全なストレージからパスワードを取得したいからです。Spring Boot + SpringデータでカスタムDataSourceを作成する方法

私はmydb.password.keyの値を持つカスタムデータソースmyapp.datasource.passwordを持っています。 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を使用してDBに接続しようとすると、起動時に失敗しています。

私はDBの自動設定クラス

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

を除外しようとしたが、それは、この例外をスロー

org.springframework.beans.factory.NoSuchBeanDefinitionException:という名前のBeanのEntityManagerFactoryを「利用可能

解決方法どんな助けでも大歓迎です!あなたはエンティティマネージャファクトリBeanを提供する必要が

おかげ

答えて

3

必要はありません。

あなたは

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 

そして、あなたの設定でapplication.ymlで:

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

ありがとうございます。この解決策は問題を解決しました! –

0

。 entityManagerFactoryという名前のBeanを作成するというコンベンションに従うことができます。 Spring documentationherehereにはいくつかの例があります。

データソースを持っていると仮定すると、あなたはこのように、わずかに逃げることができるかもしれません:自動設定で構築を除外する

@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; 
} 
+0

ありがとう@PaulHicksを。私たちはconfig、実装(Hibernate)にとらわれないようにしたかったのです。したがって、このルートを取らなかった。 –

関連する問題