Springboot加载自定义yml配置文件的方法

M1 使用@PropertySource + @Value

  1. @PropertySource 如果你需要多个yml文件那么只需要使用@PropertySources因为value属性支持多个yaml文件,

    作用:注解告知springboot加载自定义的yml配置文件的位置以及名称,由于springboot默认就会自动加载项目当中的application.yml文件,因此只要你的参数信息直接写在这个文件内,那么就不需要需要显式加载(不需要写这一句注解)

  2. @Value:

    作用:根据目标属性在yml文件中的全限定名来将对应的值取出装配给对应的属性

  3. @Component:

    作用:将当前类实例化到spring容器中,相当于xml配置文件中的<bean id="" class=""/>

package com.xxx.util;

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

/**
 * @author wyrctzy
 * @description 用于从配置文件中获取信息,取代IO的方式fileAssociationConfig
 * @createOn 2020/10/09
 */
@Data
@PropertySource(value = "classpath:readStandard.yml")
@Component
public class UrlForenConfig {
    @Value("${url.resObjectUrl}")
    private String resObjectUrl;
    @Value("${url.resCfgUrl}")
    private String resCfgUrl;
}

需要使用的时候只需要用@Autowired装配这个类就可以了

M2 使用@ConfigurationProperties + @PropertySource + @Value

  1. PropertySource@Value作用与方法一相同,不再赘述

  2. @ConfigurationProperties

    作用:之所以加入@ConfigurationProperties注解是因为通过设置就可以缩短之后使用@Value全限定类名长度,使用的是prefix设置前缀属性的值,现在@Value只需要指定参数名称,就可以取到值了

package com.xxx.util;

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

/**
 * @author wyrctzy
 * @description 用于从配置文件中获取信息,取代IO的方式fileAssociationConfig
 * @createOn 2020/10/09
 */
@Data
@ConfigurationProperties(prefix = "url")
@PropertySource(value = "classpath:readStandard.yml")
@Component
public class UrlForenConfig {
    @Value("${resObjectUrl}")
    private String resObjectUrl;
    @Value("${resCfgUrl}")
    private String resCfgUrl;
}

tips:@Data是lombok插件的注解,可以让类看起来更简洁,自动生成Get方法

以上,这是我参照多种方法之后归纳出觉得比较好用的,两种方法,如果后续发现更加使用的方法,会继续补充在这里,欢迎大家指正。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值