您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

Spring Boot项目中的全局变量和应用程序变量定义

Spring Boot项目中的全局变量和应用程序变量定义

经过我的探索,我找到了用于加载全局变量和应用程序变量(包括数据库配置)的此问题的解决方案。我们可以使用的最佳方法是-Spring Cloud Config服务器外部化配置。

我们可以为spring cloud config server创建一个微服务。在配置服务器中,我们可以通过两种方式创建变量和配置。

链接参考

需要在src / main / resources下创建Config文件夹。并遵循命名约定创建不同的配置文件

db,properties,db-test.properties,db-prod.properties,db- dev.properties。我为不同的开发环境创建了示例。就像我们可以为变量和配置创建任何配置文件一样。

并在application.properties中为配置服务器添加以下内容

server.port=8888
spring.profiles.active=native

在配置服务器的pom.xml文件添加配置服务器依赖项,

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-config-server</artifactId>
</dependency>

将以下内容添加到主应用程序运行类中,

@SpringBootApplication
@EnableConfigServer
public class ConfigServerApplication {

    public static void main(String[] args) {
    SpringApplication.run(ConfigServerApplication.class, args);
    }
}

<dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-config</artifactId>
</dependency>

在application.properties文件添加以下行,以将客户端设置为从服务器接收配置,

server.port=8080
spring.application.name=db
spring.cloud.config.uri=localhost:8888

最后,通过指定profile运行客户项目,

java -jar -Dsping.profiles.active=<profile> <jar_name>.jar

提前致谢

Java 2022/1/1 18:53:00 有431人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶