Springboot-配置获取和刷新

Springboot-配置获取和刷新

本文中配置使用注解获取
主要使用了@Value,@PropertySource,@RefreshScope和@PropertySource这些注解

从默认配置文件的获取

AppConfig

// lombox
@ToString
// 将bean注册到容器
@Component
public class AppConfig {
   
    // 获取注解所含字段
    // 当biz.name不存在的时候会报错
    @Value("${biz.name}")
    private String name;
    // 设置默认值
    @Value("${biz.unset:default}")
    private String unset;
}

application.yml

biz:
  name: configrefresh

测试结果
测试结果
如果将默认配置文件换成properties格式也一样这里就不写了

从自定义配置文件获取

在resources路径下
创建config.properties
config.properties
这好像没有这个格式的代码块贴张图讲究一下
创建config.yml

jdbc:
  url: jdbc:mysql://localhost:3306/javacode2018?characterEncoding=UTF-8
  username: javacode
  password: javacode
  reset: ${
   random.uuid}

为了方便这里的内容就设置成一样了
然后创建bean来接收参数
通过@Value实现
通过@PropertySource指定配置文件及其字符集

package cn.edu.zucc.demo.data;

import lombok.ToString;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;

/**
 * @author crabxyj
 * @date 2020/5/17 18:49
 */
@ToString
@Component
@PropertySource(value = {
   "classpath:config.properties"})
public class PropertiesData {
   
    @Value("${jdbc.url}")
    private String url;
    @Value("${jdbc.username}")
    private String username;
    @Value("${jdbc.password}")
    private String password;
    @Value("${jdbc.reset}")
    private String reset;
}

运行结果
在这里插入图片描述
如果参数少的话没有任何问题,当参数数量多的时候一个个的去写@Value会把人逼疯的

package cn.edu.zucc.demo.data;

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

/**
 * @author crabxyj
 * @date 2020/5/17 18:49
 */
@ToString
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值