SpringBoot多环境配置yml文件以及引用外部配置文件的两种方式,以及读取yml配置内容

本文详细介绍如何在Spring Boot项目中配置多环境,包括开发、测试和生产环境,通过修改yml和pom文件实现不同环境的切换。同时,介绍了两种引用外部yml配置文件的方法。

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

多环境配置

  1. 配置yml文件:
  • appointment.yml
  • appointment-dev.yml(开发环境)
  • appointment-test.yml(测试环境)
  • appointment-prod.yml(正式环境)
    yml文件
  1. yml示例
    application.yml 示例:
    注意:配置多环境yml 文件必须是application开头文件
    spring:
    	profiles:
    	 	active: @spring.profiles.active@
    
    application-dev.yml 示例:
    server:
    	port: 8081
    
    application-test.yml 示例:
    server:
    	port: 8083
    
    application-prod.yml 示例:
    server:
    	port: 8082
    
    pom文件示例:
    默认激活dev测试环境
    <profiles>
    	<profile>
    		<id>dev</id>
    		<activation>
    			<!--默认激活-->
    			<activeByDefault>true</activeByDefault>
    		</activation>
    		<properties>
    			<spring.profiles.active>dev</spring.profiles.active>
    		</properties>
    	</profile>
    
    	<!--测试环境-->
    	<profile>
    		<id>test</id>
    		<properties>
    			<spring.profiles.active>test</spring.profiles.active>
    		</properties>
    	</profile>
    
    	<!--生产环境-->
    	<profile>
    		<id>prod</id>
    		<properties>
    			<spring.profiles.active>prod</spring.profiles.active>
    		</properties>
    	</profile>
    </profiles>
    
    修改好yml以及pom文件之后,运行 mvn package -P test ,-P 之后值为环境的ID,比如dev是开发环境,prod是正式环境(由于直接runSpringBoot项目主类是开发环境,所以本次采用打包方式),不同环境,只需更改-P环境变量的值即可。
    启动打包好的jar包
    直接运行 java -jar xxx.jar 即可:
    在这里插入图片描述
    可以看到,我们mvn package -P test,打包测试环境的yml配置文件,启动端口正是之前配置的8083,达到了我们实现多环境配置的效果。

引用外部yml配置文件的两种方式

1.第一种:
创建application-common.yml 文件
修改application.yml文件,如:

spring:
  profiles:
    active: @spring.profiles.active@
    include: common

include:common common 是application-后缀,此方式必须是application开头yml文件

测试引用外部配置文件

编辑 application-common.yml,如:

common:
  test: 外部yml文件测试common

编写一个class,Common类,然后使用@Value注入的方式来获取application-common.yml 内容

@Component
public class Common {

    @Value("${common.test}")
    private String test;

    public String getTest() {
        return test;
    }

    public void setTest(String test) {
        this.test = test;
    }
}

编写一个controller,TestController,如:

@RestController()
public class TestController {

    @Autowired
    Common common;

    @GetMapping("/test")
    public String test() {

        return common.getTest();
    }
}

启动项目,并且调用该请求127.0.0.1:8081/test,如:
调用结果
可见成功获取application-common.yml 文件中common.test key值内容
2.第二种引用外部yml文件方式
Spring Framework有两个类加载YAML文件,YamlPropertiesFactoryBean和YamlMapFactoryBean
本次我们使用YamlPropertiesFactoryBean来引用
首先编写一个yml文件,并且在配置文件中写入数据,如config.yml:
在这里插入图片描述
然后,在任意spring 容器启动可加载的地方,编写如下代码:

SpringBootApplication
public class DemoApplication {

	@Bean
	public static PropertySourcesPlaceholderConfigurer properties() {
		PropertySourcesPlaceholderConfigurer configurer = new PropertySourcesPlaceholderConfigurer();
		YamlPropertiesFactoryBean yaml = new YamlPropertiesFactoryBean();
		yaml.setResources(new ClassPathResource("config.yml"));
		configurer.setProperties(yaml.getObject());
		return configurer;
	}

	public static void main(String[] args) {
		SpringApplication.run(DemoApplication.class, args);
	}
}

代码为@Bean 代码块,new ClassPathResource(“你的配置文件名即可”)
接下来我们新建一个Class ,Config 类,如:

public class Config {
    @Value("${config.test}")
    private String test;

    public String getTest() {
        return test;
    }

    public void setTest(String test) {
        this.test = test;
    }
}

新建一个请求,如:

	@Autowired
    Config config;

    @GetMapping("/configTest")
    public String configTest() {

        return config.getTest();
    }

接下来我们启动项目并且访问configTest,如:
在这里插入图片描述
成功访问!

参考资料:
1.https://www.jianshu.com/p/d258b26ef889
2.https://yulaiz.com/spring-boot-maven-profiles/

### Spring Boot 读取配置文件方式总结 #### 方法一:`@Value` 注解 通过 `@Value` 注解可以方便地注入单个属性到类的字段中。这种方式适用于简单场景,尤其是只需要获取少量配置项的情况。例如,在 `application.properties` 或 `application.yml` 中定义如下配置: ```properties my.property=Hello, Spring Boot! ``` 或者使用 YAML 格式: ```yaml my: property: Hello, Spring Boot! ``` 可以在 Java 类中这样读取配置: ```java @Component public class MyConfig { @Value("${my.property}") private String myProperty; public void printProperty() { System.out.println(myProperty); } } ``` 这种方法的优点在于实现简单,缺点是不支持复杂的数据结构绑定[^2]。 --- #### 方法二:`@ConfigurationProperties` 注解 当需要处理一组具有相同前缀的配置时,推荐使用 `@ConfigurationProperties` 注解。它允许将多个相关联的配置映射到一个 POJO 对象上。例如,假设存在以下配置: ```yaml my: app: name: MyApp version: 1.0.0 list: - item1 - item2 ``` 可以通过创建对应的实体类来绑定这些配置: ```java @ConfigurationProperties(prefix = "my.app") @Data // Lombok 自动生成 getter 和 setter public class AppConfig { private String name; private String version; private List<String> list; } ``` 接着将其注册为 Bean 并启用配置加载功能: ```java @Configuration @EnableConfigurationProperties(AppConfig.class) public class Configurer {} ``` 此方法的优势是可以轻松管理复杂的嵌套数据结构并提供类型安全的支持[^1]。 --- #### 方法三:`Environment` 接口 Spring 的 `Environment` 接口提供了另一种灵活的方式来访问应用上下文中所有的属性值。无论是在开发阶段还是生产环境中都可以利用这一机制动态调整行为逻辑。比如要获取某个特定键对应的内容可以直接调用其相应的方法: ```java @Autowired private Environment environment; public void printProperty() { String value = environment.getProperty("my.property"); System.out.println(value); } ``` 相比其他两种方式而言,虽然灵活性更高但也稍微显得不够直观简洁一些。 --- #### 方法四:`@PropertySource` 自定义资源位置 如果项目中有额外的需求需要用到外部自定义 `.properties` 文件而不是默认路径下提供的那些,则可通过声明 `@PropertySource` 来引入新的资源配置源。注意此时还需要配合 `@ComponentScan` 扫描包以及确保正确设置编码格式防止乱码等问题发生。 假设有这样一个名为 `custom-config.properties` 的文件位于项目的根目录之外的地方,并且里面包含了这样的条目: ```properties external.config=value-from-external-source ``` 那么我们就可以按照下面的样子编写代码去加载这个特殊的配置文档了: ```java @Configuration @PropertySource("file:/path/to/custom-config.properties") public class ExternalConfig { @Autowired private Environment env; public void displayExternalConfig() { System.out.println(env.getProperty("external.config")); } } ``` 这里需要注意的是,对于相对路径来说可能需要考虑不同操作系统之间的差异性;而对于绝对路径则可能会带来部署上的不便之处[^3]。 --- ### 总结表格对比 | **特性/方法** | **@Value** | **@ConfigurationProperties** | **Environment** | **@PropertySource** | |-----------------------|--------------------------|----------------------------------|---------------------------|------------------------------| | **适用范围** | 单独属性 | 复杂对象 | 动态运行期 | 非标准位置 | | **优点** | 实现简单 | 支持复杂数据 | 灵活 | 可导入外部文件 | | **局限性** | 不支持复杂结构 | 需要显式开启 | 较繁琐 | 路径依赖可能导致移植困难 | ---
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值