Spring-boot中利用外部配置文件生成数据源

Spring data 提供了一种很强大的JPA(主要是不需要给方法写implements)
Spring boot则提供了方便的自动配置。 netgloo 的例子 如何只利用一个单一的配置文件 application.properties 数据访问功能。
不过有时,你需要的是datasource是外部可配置的,而不是写死在project中的。
所以,这里博主便提供一种通过外部配置文件产生数据源来替换Spring boot自动生成的数据源。

第一步

在工程中生成一个Spring boot默认需要的配置文件: src/main/resources/application.properties

    spring.datasource.url = jdbc:postgresql://localhost:5432/bmsc
    spring.datasource.username = aere
    spring.datasource.password = aerexu

    spring.datasource.testWhileIdle = true
    spring.datasource.validationQuery = SELECT 1

    spring.jpa.properties.datasource.driver-class-name=org.postgresql.Driver
    spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.PostgreSQL9Dialect

    # Show or not log for each sql query
    spring.jpa.show-sql = true

    # Hibernate ddl auto (create, create-drop, update)
    spring.jpa.hibernate.ddl-auto = update

    # Naming strategy
    spring.jpa.hibernate.naming-strategy = org.hibernate.cfg.ImprovedNamingStrategy

第二步

在其他路径生成一个需要的配置文件C:\Users\test\Workplace\config\SpringAll\datasource.properties

spring.datasource.url = jdbc:postgresql://192.168.99.100:5432/bmsc
spring.datasource.username = aere
spring.datasource.password = aerexu

最后一步

生成一个Spring的配置类 PersistenceJPAConfig

    package com.aere.spring.all.config.jpa;

    // Imports ...

    @Configuration
    @ComponentScan
    @PropertySource(value = {"classpath:/application.properties",
            "file:/C:\\Users\\test\\Workplace\\config\\SpringAll\\datasource.properties"},
            ignoreResourceNotFound = true)
    public class PersistenceJPAConfig {

        @Bean
        @ConfigurationProperties(prefix="spring.datasource")
        public DataSource dataSource() {
            return new DriverManagerDataSource();
        }
    }

你可能会注意到在@PropertySource中有两个配置文件。当然,实际有限的只会是一个。如果两个文件都存在,则后面一个文件有效;如果只有一个文件存在,当然是存在的那个有限。这么做的目的的便于在开发中使用工程中的默认的配置文件,而在测试、部署中利用外部的配置文件。

好啦,这就是所有步骤了。是不是很简单,只用了一些小技巧?无论如何,简洁有效的代码才是最好的。

另外:

如果你需要显示出来的密码是加密过的,那你可以自定义一个Datasource类继承上面的 DriverManagerDataSource. 如下所示:

public class EncryptedDriverManagerDataSource extends DriverManagerDataSource{
    ...
    public EncryptedDriverManagerDataSource(String url, String username, String password) {
        setUrl(url);
        setUsername(username);
        String decryptedPass = someDecryptMethod(password);
        setPassword(decryptedPass);
    }
    ...
}

把上面类 PersistenceJPAConfigDriverManagerDataSource 替换成 EncryptedDriverManagerDataSource

你可能感兴趣的:(Spring-boot中利用外部配置文件生成数据源)