面试题答案
一键面试实现步骤
- 引入依赖:
- 如果不使用Spring Cloud Config,仅在Spring Boot应用内实现动态配置刷新,需要引入
spring - boot - actuator
依赖。在pom.xml
中添加如下配置:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId> </dependency>
- 如果不使用Spring Cloud Config,仅在Spring Boot应用内实现动态配置刷新,需要引入
- 配置暴露端点:
- 在
application.properties
或application.yml
中配置暴露刷新配置的端点。例如在application.yml
中:
management: endpoints: web: exposure: include: refresh
- 在
- 定义可刷新的配置类:
- 创建一个配置类,使用
@ConfigurationProperties
注解绑定配置属性,并确保该类可以被Spring容器管理。例如:
import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.annotation.Configuration; @Configuration @ConfigurationProperties(prefix = "custom.config") public class CustomConfig { private String someValue; public String getSomeValue() { return someValue; } public void setSomeValue(String someValue) { this.someValue = someValue; } }
- 创建一个配置类,使用
- 使用配置属性:
- 在需要使用该配置的组件中注入
CustomConfig
。例如在一个服务类中:
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class MyService { @Autowired private CustomConfig customConfig; public void doSomething() { System.out.println("Custom value: " + customConfig.getSomeValue()); } }
- 在需要使用该配置的组件中注入
- 触发配置刷新:
- 可以通过发送POST请求到
/actuator/refresh
端点来触发配置刷新。例如使用curl
命令:
curl -X POST http://localhost:8080/actuator/refresh
- 可以通过发送POST请求到
关键技术点
- Spring Boot Actuator:提供了生产就绪(production - ready)的特性,如健康检查、指标监控、端点暴露等功能。
/actuator/refresh
端点用于刷新配置属性。 - @ConfigurationProperties:用于将配置文件中的属性值绑定到Java对象,方便管理和使用配置。
- 配置管理:如果应用规模较大,可能需要借助Spring Cloud Config等工具来集中管理配置,实现更灵活的配置动态更新,如不同环境的配置管理、版本控制等。但仅在应用内实现简单的动态配置刷新,Spring Boot Actuator通常已足够。
如果使用Spring Cloud Config:
- 搭建Spring Cloud Config Server:
- 创建一个Spring Boot项目,引入
spring - cloud - config - server
依赖。 - 在
application.yml
中配置服务器相关信息,如配置文件存储位置(可以是Git仓库等)。
- 创建一个Spring Boot项目,引入
- 客户端配置:
- 在Spring Boot应用(客户端)中引入
spring - cloud - starter - config
依赖。 - 配置
bootstrap.properties
或bootstrap.yml
,指定Config Server的地址和应用的配置信息,例如:
spring: application: name: my - application cloud: config: uri: http://config - server - address:port fail - fast: true
- 在Spring Boot应用(客户端)中引入
- 配置刷新:
- 同样借助Spring Boot Actuator的
/actuator/refresh
端点来刷新配置,但此时刷新的是从Config Server获取的配置。并且可以通过在Config Server端更新配置文件,客户端通过刷新端点获取最新配置。
- 同样借助Spring Boot Actuator的