温馨提示×

温馨提示×

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

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

Spring Boot如何扩展配置

发布时间:2026-11-04 14:47:21 来源:亿速云 阅读:99 作者:小樊 栏目:软件技术

在 Spring Boot 中,“扩展配置”通常指在不修改框架默认行为的前提下,增加、覆盖或定制配置能力。下面从常见场景 + 实现方式系统说明。


一、扩展配置文件来源

1. 多环境配置(最常用)

# application.yml
spring:
  profiles:
    active: dev
---
spring:
  profiles: dev
server:
  port: 8080
---
spring:
  profiles: prod
server:
  port: 80

2. 外部配置文件

Spring Boot 默认加载顺序(后者覆盖前者):

  1. file:./config/
  2. file:./
  3. classpath:/config/
  4. classpath:/

也可指定:

java -jar app.jar --spring.config.location=/opt/app/config/

3. 自定义配置文件名

--spring.config.name=myapp

二、使用 @ConfigurationProperties 扩展自定义配置

1. 定义配置类

@ConfigurationProperties(prefix = "app")
@Component
public class AppConfig {
    private String name;
    private int timeout;
    // getter / setter
}

2. 配置文件中使用

app:
  name: demo
  timeout: 3000

3. 启用(Spring Boot 2.2+ 可省略)

@EnableConfigurationProperties(AppConfig.class)

三、通过 @PropertySource 加载额外配置

@Configuration
@PropertySource("classpath:extra.properties")
public class ExtraConfig {
}

⚠️ 注意:

  • 不支持 YAML
  • 加载顺序早于 application.yml

四、编程方式扩展配置(Environment)

1. 动态添加配置

@Autowired
Environment env;

Map<String, Object> map = new HashMap<>();
map.put("app.dynamic", "value");

((ConfigurableEnvironment) env)
    .getPropertySources()
    .addFirst(new MapPropertySource("dynamic", map));

五、扩展自动配置(AutoConfiguration)

1. 自定义 Starter

my-spring-boot-starter
├── spring.factories
└── MyAutoConfiguration

spring.factories:

org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.example.MyAutoConfiguration

2. 条件化配置

@Configuration
@ConditionalOnClass(RedisTemplate.class)
@ConditionalOnProperty(prefix = "app.redis", name = "enabled")
public class RedisAutoConfig {
}

六、扩展配置中心(高级)

常见方案

  • Spring Cloud Config
  • Nacos
  • Apollo
  • Consul

示例(Nacos):

spring:
  cloud:
    nacos:
      config:
        server-addr: localhost:8848

七、监听配置变化(热更新)

@RefreshScope
@RestController
public class ConfigController {

    @Value("${app.name}")
    private String name;
}

(需 Spring Cloud)


八、总结对照表

需求 推荐方式
多环境 profiles
自定义参数 @ConfigurationProperties
外部配置 config.location
动态配置 Environment
框架扩展 AutoConfiguration
配置中心 Nacos / Apollo

如果你有具体场景(如:动态配置、多模块、配置加密、K8s 配置),我可以给更针对性的方案。

向AI问一下细节

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

AI
助
手