从配置文件中获取属性应该是 SpringBoot 开发中最为常用的功能之一,但就是这么常用的功能,仍然有很多开发者抓狂~今天带大家简单回顾一下这六种的使用方式:
一、Environment
注入 Environment 类调用其方法 getProperty(属性 key)即可
@Slf4j@SpringBootTestpublic class EnvironmentTest {
@Resource private Environment env;
@Test public void var1Test() { String var1 = env.getProperty("env.var1"); log.info("Environment获取的配置内容:{}", var1); }}
复制代码
二、@Value 注解
只要在变量上加注解 @Value("${env.var1}")就可以了,@Value 注解会自动将配置文件中的 env.var1 属性值注入到 var1 字段中。
@Slf4j@SpringBootTestpublic class EnvVariablesTest {
@Value("${env.var1}") private String var1; @Test public void var1Test(){ log.info("配置文件属性: {}",var1); }}
复制代码
三、@ConfigurationProperties 注解
在 application.yml 配置文件中添加配置项:
env: var1: 变量值1 var2: 变量值2
复制代码
创建一个 MyConf 类用于承载所有前缀为 env 的配置属性。
@Data@Configuration@ConfigurationProperties(prefix = "env")public class MyConf {
private String var1; private String var2;}
复制代码
在需要使用 var1、var2 属性值的地方,将 MyConf 对象注入到依赖对象中即可。
@Slf4j@SpringBootTestpublic class ConfTest {
@Resource private MyConf myConf;
@Test public void myConfTest() { log.info("@ConfigurationProperties注解获取的配置内容:{}", JSON.toJSONString(myConf)); }}
复制代码
四、@PropertySources 注解
在 src/main/resources/ 目录下创建自定义配置文件 important.properties,增加两个属性。
env.var1=变量值1env.var2=变量值2
复制代码
在需要使用自定义配置文件的类上添加 @PropertySources 注解,注解 value 属性中指定自定义配置文件的路径,可以指定多个路径,用逗号隔开。
@Data@Configuration@PropertySources({ @PropertySource(value = "classpath:important.properties", encoding = "utf-8"), @PropertySource(value = "classpath:important.properties",encoding = "utf-8")})public class PropertySourcesConf {
@Value("${env.var1}") private String var1;
@Value("${env.var2}") private String var2;}
复制代码
五、YamlPropertiesFactoryBean 加载 YAML 文件
@Configurationpublic class MyYamlConfig {
@Bean public static PropertySourcesPlaceholderConfigurer yamlConfigurer() { PropertySourcesPlaceholderConfigurer configurer = new PropertySourcesPlaceholderConfigurer(); YamlPropertiesFactoryBean yaml = new YamlPropertiesFactoryBean(); yaml.setResources(new ClassPathResource("test.yml")); configurer.setProperties(Objects.requireNonNull(yaml.getObject())); return configurer; }}
复制代码
可以通过 @Value 注解或 Environment.getProperty() 方法来获取其中定义的属性值。
@Slf4j@SpringBootTestpublic class YamlTest {
@Value("${env.var3}") private String var3;
@Test public void myYamlTest() { log.info("Yaml获取配置内容:{}", var3); }}
复制代码
六、JAVA 原生读取
@Slf4j@SpringBootTestpublic class CustomTest {
@Test public void customTest() { Properties props = new Properties(); try { InputStreamReader inputStreamReader = new InputStreamReader( this.getClass().getClassLoader().getResourceAsStream("test.properties"), StandardCharsets.UTF_8); props.load(inputStreamReader); } catch (IOException e1) { System.out.println(e1); } log.info("Properties Name:" + props.getProperty("env.appName")); }}
复制代码
作者:京东零售 马宏伟
来源:京东云开发者社区 转载请注明来源
评论