下面的代码从保险库注入数据源中获取数据库详细信息,该数据源被 liquibase 用于连接和执行脚本
构建.gradle.kts
import org.jetbrains.kotlin.gradle.tasks.KotlinCompile
plugins {
id("org.springframework.boot") version "2.4.4"
id("io.spring.dependency-management") version "1.0.11.RELEASE"
kotlin("jvm") version "1.4.31"
kotlin("plugin.spring") version "1.4.31"
}
group = "com.db"
version = "0.0.1-SNAPSHOT"
java.sourceCompatibility = JavaVersion.VERSION_1_8
configurations {
compileOnly {
extendsFrom(configurations.annotationProcessor.get())
}
}
repositories {
mavenCentral()
}
dependencies {
implementation("org.springframework.boot:spring-boot-starter-data-jpa")
implementation("org.springframework.cloud:spring-cloud-starter-bootstrap:3.0.2")
implementation("org.jetbrains.kotlin:kotlin-reflect")
implementation("org.jetbrains.kotlin:kotlin-stdlib-jdk8")
implementation("org.liquibase:liquibase-core:4.3.2")
implementation(files("libs/ojdbc6.jar"))
implementation("org.springframework.cloud:spring-cloud-starter-vault-config:3.0.2")
}
tasks.withType<KotlinCompile> {
kotlinOptions {
freeCompilerArgs = listOf("-Xjsr305=strict")
jvmTarget = "1.8"
}
}
tasks.withType<Test> {
useJUnitPlatform()
}
引导程序属性
spring.cloud.vault.application-name=database-config
spring.cloud.vault.token=XXXXX
spring.cloud.vault.scheme=http
spring.cloud.vault.kv.enabled=true
spring.cloud.vault.host=localhost
spring.cloud.vault.port=8200
应用程序属性
logging.level.liquibase=DEBUG
spring.liquibase.change-log=classpath:db/changelog.xml
spring.liquibase.enabled=true
VaultDBConfig
import org.springframework.boot.context.properties.ConfigurationProperties
@ConfigurationProperties("db")
class VaultDBConfig {
var username: String? = null
var password: String? = null
var url: String? = null
}
数据库配置
import oracle.jdbc.pool.OracleDataSource
import java.sql.SQLException
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.context.annotation.Primary
import org.springframework.context.annotation.Profile
import org.springframework.core.env.Environment
import javax.sql.DataSource
@Configuration
class DatabaseConfig(private val dbDetails: VaultDBConfig, private val environment: Environment) {
val logger: Logger = LoggerFactory.getLogger(DatabaseConfig::class.java)
@Primary
@Bean
@Throws(SQLException::class)
fun dataSource(): DataSource? {
val oracleDataSource = OracleDataSource()
oracleDataSource.setURL(dbDetails.url)
oracleDataSource.setUser(dbDetails.username)
oracleDataSource.setPassword(dbDetails.password)
return oracleDataSource
}
}
在 application.kt 中启用配置属性
@SpringBootApplication
@EnableConfigurationProperties(VaultDBConfig::class)
class ConfigApplication
fun main(args: Array<String>) {
runApplication<ConfigApplication>(*args)
}
保险柜插入
vault kv put secret/database-config db.username=xxx db.password=xxx dp.url=xxx