Spring Boot 菜鸟教程 28 多配置文件

本文介绍了在Spring Boot项目中如何管理多个配置文件,包括`application.properties`、`application-test.properties`和`application-dev.properties`,以适应开发和部署的不同需求。通过设置`spring.profiles.active`来切换配置,并提供了测试类`MultipartPropertiesTest1`和`MultipartPropertiesTest2`的示例。此外,还分享了项目源码地址和其他关联教程链接。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

GitHub

src="//ghbtns.com/github-btn.html?user=je-ge&repo=spring-boot&type=watch&count=true" scrolling="0" width="110" height="20">

需求产生

开发过程中可能会有如下需求:开发和部署的配置信息可能不同,常规的方式就是在配置文件里面先写好开发配置,在部署的时候再去修改这些配置,这样可能会出现很多问题,比如用户名、密码忘记了修改或者改错了等问题。

项目结构图片

这里写图片描述

application.properties

spring.profiles.active=test

核心配置文件里面的spring.profiles.active=test这个设置表示系统默认使用test(即application-test.properties)中的配置。

application-test.properties

jdbc.username=rootTest
jdbc.password=rootTest

application-dev.properties

jdbc.username=rootDev
jdbc.password=rootDev

MultipartPropertiesTest1.java

package com.jege.spring.boot;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

/**
 * @author JE哥
 * @email 1272434821@qq.com
 * @description:
 */
@RunWith(SpringRunner.class)
@SpringBootTest
public class MultipartPropertiesTest1 {
  @Value("${jdbc.username}")
  private String username;
  @Value("${jdbc.password}")
  private String password;

  @Test
  public void config() {
    System.out.println("当前的用户名是: " + username);
    System.out.println("当前的密码是: " + password);
  }
}

MultipartPropertiesTest2.java

package com.jege.spring.boot;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringRunner;

/**
 * @author JE哥
 * @email 1272434821@qq.com
 * @description:
 */
@RunWith(SpringRunner.class)
@SpringBootTest
@ActiveProfiles("dev")
public class MultipartPropertiesTest2 {
  @Value("${jdbc.username}")
  private String username;
  @Value("${jdbc.password}")
  private String password;

  @Test
  public void config() {
    System.out.println("当前的用户名是: " + username);
    System.out.println("当前的密码是: " + password);
  }
}

其他关联项目

源码地址

https://github.com/je-ge/spring-boot

如果觉得我的文章或者代码对您有帮助,可以请我喝杯咖啡。
您的支持将鼓励我继续创作!谢谢!
微信打赏
支付宝打赏

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值