mybatis-generator如何从环境变量中使用数据库密码

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 启动就可以了


也许有更好的方法,望指教!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值