SpringBoot笔记:@Value、@ConfigurationProperties、@PropertySource 配置参数的几种方式

yml格式文件

这里如果使用的 yml 格式文件测试,其实 yml 和 properties 文件使用上没有本质区别,仅仅是格式不同,本文使用的是 yml 文件进行的测试。l格式文件配置信息如下,其中test是这次要解析的字段:

#端口,项目上下文
server:
  port: 8080
  servlet:
    context-path: /helloworld-demo

test:
  name: 云天明
  age: 18
  address: 河南省郑州市

方式一:@ConfigurationProperties注解方式

使用ConfigurationProperties来获取配置文件的字段,参数prefix代表配置的前缀,@Data使用是的是lombok插件

package com.demo.config;

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

/**
 * 获取自定义配置方法一
 */
@Data
@Component
// 如果是外部配置文件(非application.yml 文件)可以用下面这个注解把配置文件引入进来
// @PropertySource(value = {"classpath:config/test.properties"})
@ConfigurationProperties(prefix = "test")
public class MyConfig1 {
    private String name;
    private Integer age;
    private String address;
}

方式二:@Value注解方式

package com.demo.config;

import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

/**
 * 获取自定义配置方法二
 */
@Data
@Component
public class MyConfig2 {
    @Value("${test.name}")
    private String name;
    @Value("${test.age}")
    private Integer age;
    @Value("${test.address}")
    private String address;
}

方式三:Environment获取方式

package com.demo.config;

import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

/**
 * 获取自定义配置方法二
 */
@Component
@Configuration
public class MyConfig3 {
    @Autowired
    Environment env;
    
    public String getName() {
        return env.getProperty("test.name");
    }
    public Integer getAge() {
        return env.getProperty("test.age", Integer.class);
    }
    public String getAddress() {
        return env.getProperty("test.address");
    }
}

测试结果

    @Autowired
    MyConfig1 myConfig1;
    @Autowired
    MyConfig2 myConfig2;
    @Autowired
    MyConfig3 myConfig3;

    @RequestMapping("/getMyconfig")
    public void getMyconfig() throws IOException {
        log.info("Myconfig1 姓名:{},年龄:{},住址:{}", myConfig1.getName(), myConfig1.getAge(), myConfig1.getAddress());
        log.info("Myconfig2 姓名:{},年龄:{},住址:{}", myConfig2.getName(), myConfig2.getAge(), myConfig2.getAddress());
        log.info("Myconfig3 姓名:{},年龄:{},住址:{}", myConfig3.getName(), myConfig3.getAge(), myConfig3.getAddress());
    }

测试结果:

2021-01-07 20:56:13.666  INFO 50108 --- [nio-8080-exec-1] com.demo.controller.TestController       : Myconfig1 姓名:云天明,年龄:18,住址:河南省郑州市
2021-01-07 20:56:13.668  INFO 50108 --- [nio-8080-exec-1] com.demo.controller.TestController       : Myconfig2 姓名:云天明,年龄:18,住址:河南省郑州市
2021-01-07 20:56:13.670  INFO 50108 --- [nio-8080-exec-1] com.demo.controller.TestController       : Myconfig3 姓名:云天明,年龄:18,住址:河南省郑州市

propetries格式文件

如果是properties文件,以上的方法也是可以使用的,下面这篇文章中提供了多种获取resources目录下文件的方式
《如何读取resources目录下的文件路径(九种方式)》
获取propetries内容前提就是首先获取propetries,配置文件记得使用UTF-8编码,以免出现乱码问题

方法四:通过文件流配合Properties类读取

主要思想是获取文件inputStream流,然后使用Properties类load方式读取,测试代码如下:

    @RequestMapping("/getMyconfig4")
    public void getMyconfig4() {
        //通过这种方式获取文件流
        try(InputStream inputStream = ClassLoader.getSystemResourceAsStream("test.properties")){
            Properties prop = new Properties();
            //指定编码为UTF-8以防中文乱码
            prop.load(new InputStreamReader(inputStream, "UTF-8"));
            String name = prop.getProperty("test.name");
            String age = prop.getProperty("test.age");
            String address = prop.getProperty("test.address");
            log.info("Myconfig4 姓名:{},年龄:{},住址:{}", name, age, address);
        }catch (Exception e){
            log.error("获取配置文件失败",e);
        }
    }

测试结果:

2021-01-07 21:46:16.447  INFO 4568 --- [nio-8080-exec-4] com.demo.controller.TestController       : Myconfig4 姓名:云天明,年龄:18,住址:河南省郑州市

方法五:通过ResourceBundle类读取

通过 ResourceBundle.getBundle(“test”)直接过去配置文件,并且读取配置文件内容。

    @RequestMapping("/getMyconfig5")
    public void getMyconfig5() {
        try {
            //注意这里的test只有文件名不带类型
            ResourceBundle resource = ResourceBundle.getBundle("test");
            String name = changeToUTF8(resource.getString("test.name"));
            String age = changeToUTF8(resource.getString("test.age"));
            String address = changeToUTF8(resource.getString("test.address"));
            log.info("Myconfig5 姓名:{},年龄:{},住址:{}", name, age, address);
        } catch (Exception e) {
            log.error("获取配置文件失败", e);
        }
    }

    /**
     * 将原来编码为8859-1字符串转为UTF-8编码
     *
     * @param str
     * @return
     */
    private String changeToUTF8(String str) throws UnsupportedEncodingException {
        if (str == null) {
            return null;
        }
        return new String(str.getBytes("ISO8859-1"));
    }

测试结果:

2021-01-07 22:12:56.178  INFO 36044 --- [nio-8080-exec-2] com.demo.controller.TestController       : Myconfig5 姓名:云天明,年龄:18,住址:河南省郑州市
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

leo825...

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值