SpringBoot 中从application.yml中获取自定义常量

本文介绍了如何使用Spring Boot从application.yml文件中加载配置,并通过一个具体示例展示了配置的读取过程。需要注意的是,在YAML文件中配置项应采用短横线分隔而非驼峰命名法。

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

今天尝试了一下从application.yml获取配置的常量,因为刚接触不是很熟所以记录下来。

要注意的地方是 application.yml 中不能用驼峰式写法(systemParams)要改成system-params

要导入依赖

pom.xml

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

application.yml

system-params:
  image-uri: http://xxxxxx

SystemParams

package com.shior.demoshior.config;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

/**
 * @Author: zhugf
 * @Description:
 * @Date created in 2018/5/14
 */
@Component
@ConfigurationProperties(prefix = "system-params")
public class SystemParams {

    private String imageUri;

    public String getImageUri() {
        return imageUri;
    }

    public void setImageUri(String imageUri) {
        this.imageUri = imageUri;
    }
}

测试

package com.shior.demoshior.common;

import com.shior.demoshior.config.SystemParams;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

/**
 * @Author: zhugf
 * @Description:
 * @Date created in 2018/5/14
 */
@RunWith(SpringRunner.class)
@SpringBootTest
public class TestConfig {
    @Autowired
    SystemParams systemParams;
    @Test
    public void testParam(){
        System.out.println(systemParams.getImageUri());
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值