本文讲述的是在 springboot 中如何利用外部文件配置数据源。
将数据源的配置信息直接配置在项目中是不安全的,所以将数据源的配置放在外部文件中会安全很多,并且不同环境的数据源也必然不同,
所以放在外部文件中配置也是非常实用的。
定义外部配置文件
我们在 springboot 的配置文件 application.yml 中配置外部文件所在目录的路径
1 2 3 4
| external: config: file: path: /app/example/config
|
配置数据源
随后创建 Config 类,在类中引用该配置
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
| @Configuration @ConfigurationProperties(prefix = "jdbc") @PropertySource(value = {"file:${external.config.file.path}/jdbc.properties"}) @Data public class DataSourceConfig {
private String url;
private String username;
private String password;
@Bean public DataSource dataSource() { HikariConfig hikariConfig = new HikariConfig();
hikariConfig.setJdbcUrl(this.url); hikariConfig.setUsername(this.username); hikariConfig.setPassword(this.password);
hikariConfig.addDataSourceProperty("cachePrepStmts", "true"); hikariConfig.addDataSourceProperty("prepStmtCacheSize", "250"); hikariConfig.addDataSourceProperty("prepStmtCacheSqlLimit", "2048"); hikariConfig.addDataSourceProperty("useServerPrepStmts", "true"); hikariConfig.addDataSourceProperty("useLocalSessionState", "true"); hikariConfig.addDataSourceProperty("useLocalTransactionState", "true"); hikariConfig.addDataSourceProperty("rewriteBatchedStatements", "true"); hikariConfig.addDataSourceProperty("cacheResultSetMetadata", "true"); hikariConfig.addDataSourceProperty("cacheServerConfiguration", "true"); hikariConfig.addDataSourceProperty("elideSetAutoCommits", "true"); hikariConfig.addDataSourceProperty("maintainTimeStats", "false");
return new HikariDataSource(hikariConfig); } }
|
@Configuration: 表示这是一个配置类,springboot启动时会进行加载
@ConfigurationProperties(prefix = “jdbc”): 会解析配置文件中以 jdbc 为起始的参数,例如 jdbc.url等,但是 abc.name 这样的参数就不会进行解析
@PropertySource(value = {“file:${external.config.file.path}/jdbc.properties”}): 定义引用的配置文件,因为是外部配置文件,所以要用 file
${external.config.file.path} 会引用上之前在 yml 文件中配置的值
如果在配置类的属性上没有设置 @Value,则会按照属性名进行解析,所以上面这个类会自动去解析 jdbc.url, jdbc.username, jdbc.password
springboot 现在默认使用的数据库连接池框架是 hikari,所以在 datasource 方法中进行 hikari 的配置
创建外部配置文件
随后在对应的外部文件中定义配置参数就可以了
jdbc.url = jdbc:mysql://127.0.0.1:3306/baby
jdbc.username = dbuser
jdbc.password = dbpwd