How does mybatis-generator use database passwords from environment variables

How does mybatis-generator use database passwords from environment variables (using gradle)

Recently, I found that the project used to mybatis-generatorread data from the database to generate model and mapper, but the read data cannot be read from environment variables, which can easily cause sensitive data leakage, and I just learned gradle recently, so I used gradle to solve this problem by the way.

Without further ado, go directly to the code:

From the source code, you can see mybatis-generatorthat attributes can be obtained from system variables.
insert image description here
Official documents also write:

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 .The specified properties file will be searched for a matching value and the matching value will be substituted. The properties file is of the n ordinary 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. The translation: element is used to specify an external properties file ${property}for
parsing
configuration
< properties >. Any property in the configuration will accept ${ property }an attribute of the form . The specified properties file will be searched for and replaced with matching values. propertiesfile is the normal format for a Java properties file.
If there is a name conflict between a property specified here and a system property, the system property is used.

Let's start with system properties

build.gradledocument

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]
}

Finally, generatorConfig.xmlset the JVM parameters in the file.

generatorConfig.xml

//...省略
<generatorConfiguration>
		//...省略
        <jdbcConnection password="${mysqlRootPassword}"
        				driverClass="${jdbc.driverClass}"
                        connectionURL="${jdbc.connectionURL}"
                        userId="${jdbc.userId}">
			//...省略
        </jdbcConnection>
        //...省略
</generatorConfiguration>

Just start it directly with gradle run


Maybe there is a better way, please advise!

Guess you like

Origin blog.csdn.net/HHoao/article/details/126633923