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.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