0
点赞
收藏
分享

微信扫一扫

如何在Spring Boot项目中添加自定义的配置文件?

在Spring Boot项目中添加和使用自定义配置文件非常灵活,以下是几种常用方式:

1. 使用默认配置文件(推荐)

Spring Boot默认读取src/main/resources下的:

  • application.properties
  • application.yml(或application.yaml

示例:application.properties

# 服务器端口
server.port=8081

# 自定义配置
app.name=MySpringApp
app.version=1.0.0
app.enabled=true

示例:application.yml(更简洁的格式)

server:
  port: 8081

app:
  name: MySpringApp
  version: 1.0.0
  enabled: true

2. 添加自定义命名的配置文件

如果需要分离配置(如数据库配置、第三方服务配置),可以创建自定义配置文件。

方式一:通过@PropertySource注解加载

创建自定义配置文件src/main/resources/config/app-config.properties

创建配置类绑定这些属性:

方式二:通过配置文件指定额外配置

在主配置文件application.properties中指定要加载的配置文件:

# 加载多个自定义配置文件
spring.config.import=classpath:config/db-config.properties,classpath:config/mq-config.properties

3. 按环境区分配置文件

Spring Boot支持按环境加载不同配置文件,命名规则:application-{profile}.properties

  1. 创建环境配置文件:
  • application-dev.properties(开发环境)
  • application-test.properties(测试环境)
  • application-prod.properties(生产环境)
  1. 指定激活的环境:
  • application.properties中添加:spring.profiles.active=dev
  • 启动时通过命令行指定:java -jar app.jar --spring.profiles.active=prod

4. 使用配置的两种方式

方式一:通过@Value注解直接获取

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class ConfigController {

    // 从默认配置文件获取
    @Value("${app.name}")
    private String appName;
    
    // 从自定义配置文件获取
    @Value("${app.max-connections}")
    private int maxConnections;

    @GetMapping("/config")
    public String getConfig() {
        return "App Name: " + appName + ", Max Connections: " + maxConnections;
    }
}

方式二:通过@ConfigurationProperties绑定(推荐批量使用)

如前面创建的AppConfig类,在需要使用的地方直接注入:

@RestController
public class AppController {

    private final AppConfig appConfig;
    
    // 构造函数注入
    public AppController(AppConfig appConfig) {
        this.appConfig = appConfig;
    }

    @GetMapping("/app-info")
    public String getAppInfo() {
        return "Timeout: " + appConfig.getTimeout() + 
               ", Tracking: " + appConfig.getFeature().isTrackingEnabled();
    }
}

注意事项

  1. 配置文件路径优先级:外部配置 > 内部配置,具体可参考Spring Boot官方文档
  2. 使用@ConfigurationProperties需要添加依赖(Spring Boot 2.2+已默认包含):

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-configuration-processor</artifactId>
    <optional>true</optional>
</dependency>

  1. 配置项命名推荐使用小写字母加连字符(如max-connections),绑定到Java类时会自动转换为驼峰命名(maxConnections

通过以上方法,你可以灵活地管理Spring Boot项目中的各种配置。

举报

相关推荐

0 条评论