springboot项目中获取自定义的properties文件的属性

准备工作

  1. properties文件

  2. 映射properties文件的配置类

  3. 使用到的关键注解

    1. @Component //将bean交给spring管理
    2. @ConfigurationProperties(prefix = “前缀”) //除了前缀属性外,还可以添加其它属性,有想法的同学可以查看源码。
     作用:将该类与外部配置文件绑定起来,就是与properties文件绑定起来
    

    在这里插入图片描述

    1. @PropertySource(“classpath:config.properties”) // 指定外部配置文件的路径

应用示例

properties文件

config.name=liql
config.age=10

在这里插入图片描述

映射properties文件的配置类

配置类需要getter setter方法,且不需要与properties保持完全一致
注意注解的使用

package com.li;

/**
 * @author liql
 * @date 2021/6/29
 */

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

@Component
@ConfigurationProperties(prefix = "config")  //properties 文件中的前缀为config
@PropertySource("classpath:config.properties")  //properties 文件路径
public class TestProperties {
    String name;
    int age;
    String color;//多出来的一个属性

    public String getColor() {
        return color;
    }

    public void setColor(String color) {
        this.color = color;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}

测试

代码

package com.li;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

@SpringBootTest
class TestpropertiesApplicationTests {

    @Autowired
    TestProperties testProperties;
    @Test
    void contextLoads() {
        System.out.println("age="+testProperties.age);
        System.out.println("name="+testProperties.name);

        //由于color属性在properties文件中没有注明,所以映射结果为空。
        System.out.println("color="+testProperties.color+"  由于color属性在properties文件中没有注明,所以映射结果为空");
    }

}


测试结果

在这里插入图片描述在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值