我目前正在构建一个 Spring Boot 应用程序,它需要在三种不同的数据库环境中工作,并且以与环境无关的方式运行。
“开发”环境将使用本地 sqlite 数据库。
“uat”环境将使用 postgres 数据库。
“实时”环境将使用 sql 数据库。
加载时,我的应用程序检查是否存在环境参数:
如果未设置或环境参数为 dev,则它将创建一个本地 sqlite 数据库并在 session 期间建立与其的连接。
如果设置为 uat,则将建立与 heroku postgres 数据库的连接。
如果设置为 live,则将建立到 mysql 数据库的连接。
现在我正在努力在 Java 上将其概念化。
这是我到目前为止编写的代码,我在其中获取环境参数。除此之外我不确定。
@SpringBootApplication
public class Launcher implements CommandLineRunner {
public static void main(String args[]) {
SpringApplication.run(Launcher.class, args);
}
@Override
public void run(String... args) throws Exception {
String currentEnvironment = System.getenv("CURRENT_ENV");
// if current env is null or dev, set up sqlite database (if it doesnt already exist and use this for the remainder of the session
// if uat connect to heroku postgres db
// if live then connect to mysql db
}
}
最佳答案
这就是在 spring 中创建配置文件的目的,Spring Boot 允许您拥有有助于您的应用程序在不同环境中运行的配置文件。
因此,在您的情况下,您必须创建三个属性文件,例如
dev.properties
uat.properties
live.properties
在每个属性文件中,您必须为开发设置必要的配置。然后只需激活您想要工作的配置文件。
spring.profiles.active=dev
我会为每一个创建一个@Configuration 类。
@Profile("dev")
@Configuration
public class DevConfiguration{
...
}
@Profile("uat")
@Configuration
public class UatConfiguration{
...
}
@Profile("live")
@Configuration
public class LiveConfiguration{
...
}
我想提一本好书Pro Spring Boot由 Felipe Gutierrez 撰写,它可以教给您很多东西。
关于java - 设置 Spring Boot 应用程序以根据 session 的环境参数连接到不同的数据源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51697949/