mybatis-generator如何从环境变量中使用数据库密码(使用gradle)
最近发现项目中使用mybatis-generator
从数据库中读取数据生成model和mapper, 但是读取数据却不能从环境变量中读取,这很容易造成敏感的数据泄漏,而最近又刚好学到了gradle, 于是顺便使用gradle来解决这个问题。
话不多说直接上代码:
从源码中可以看到mybatis-generator
可以从系统变量中获取属性
官方文档也有写:
The element is used to specify an external properties file for use in the parsing of the configuration. Any attribute in the configuration will accept a property in the form
${property}
.The specified properties file will be searched for a matching value and the matching value will be substituted. The properties file is of the normal format for a Java properties file.
If there are name collisions between a property specified here and a system property, the system property will win.
翻译:
< properties >
元素用于指定用于解析配置的外部属性文件。配置中的任何属性都将接受形式为${ property }
的属性。将在指定的属性文件中搜索匹配值,并替换匹配值。properties
文件是 Java 属性文件的正常格式。
如果此处指定的属性和系统属性之间存在名称冲突,则使用系统属性。
我们就从系统属性下手
build.gradle
文件
plugins {
id 'application'
}
dependencies {
//依赖
implementation libs.mybatis.generator.core
implementation libs.mybatis.generator.core
implementation libs.mybatis.generator.core
implementation libs.mybatis.plus.boot.starter
implementation libs.mysql.connector.java
}
application {
//设置启动类
mainClass = 'com.hhoa.blog.mgb.Generator'
// 从环境变量中获取密码, 我提前设置了MYSQL_ROOT_PASSWORD为MYSQL的密码,这里也可以使用一些加密解密手段
def mysqlRootPassword = System.getenv('MYSQL_ROOT_PASSWORD')
// JVM参数
applicationDefaultJvmArgs = ['-DmysqlRootPassword=' + mysqlRootPassword]
}
最后在generatorConfig.xml
文件中设置JVM参数就可以了
generatorConfig.xml
//...省略
<generatorConfiguration>
//...省略
<jdbcConnection password="${mysqlRootPassword}"
driverClass="${jdbc.driverClass}"
connectionURL="${jdbc.connectionURL}"
userId="${jdbc.userId}">
//...省略
</jdbcConnection>
//...省略
</generatorConfiguration>
直接使用gradle run 启动就可以了
也许有更好的方法,望指教!