温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Spring Boot中配置外部化配置中心

发布时间:2024-10-05 13:05:00 来源:亿速云 阅读:81 作者:小樊 栏目:编程语言

在 Spring Boot 中,可以通过以下步骤配置外部化配置中心(例如:Spring Cloud Config Server):

  1. 引入依赖

在 Spring Boot 项目的 pom.xml 文件中,添加 Spring Cloud Config Server 的依赖:

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-config-server</artifactId>
</dependency>
  1. 配置文件

在 Spring Boot 项目的 application.propertiesapplication.yml 文件中,添加以下配置:

对于 application.properties 文件:

spring.cloud.config.server.git.uri=https://github.com/your-repo/your-config-repo.git

对于 application.yml 文件:

spring:
  cloud:
    config:
      server:
        git:
          uri: https://github.com/your-repo/your-config-repo.git

https://github.com/your-repo/your-config-repo.git 替换为你的 Git 仓库地址。

  1. 启动类

确保你的 Spring Boot 项目的主类上添加了 @EnableConfigServer 注解:

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.config.server.EnableConfigServer;

@SpringBootApplication
@EnableConfigServer
public class ConfigServerApplication {
    public static void main(String[] args) {
        SpringApplication.run(ConfigServerApplication.class, args);
    }
}
  1. 配置客户端

在客户端 Spring Boot 项目中,添加以下依赖:

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

在客户端项目的 bootstrap.propertiesbootstrap.yml 文件中,添加以下配置:

对于 bootstrap.properties 文件:

spring.cloud.config.uri=http://localhost:8888

对于 bootstrap.yml 文件:

spring:
  cloud:
    config:
      uri: http://localhost:8888

http://localhost:8888 替换为你的 Config Server 地址。

现在,客户端项目将从外部化配置中心获取配置信息。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI