现在开发主要使用微服务框架springboot,在springboot中经常遇到读取application.yml文件的情形。

一、概述

开发过程中经常遇到要读取application.yml文件中的属性值,本文总结几种读取的方式,供参考。

二、详述

我这里使用的是springboot-2.1.2.RELEASE版本,这里使用的是application.properties的配置方式,和使用application.yml的方式是一样的。下面是application.properties文件的内容

cn.com.my.test1=test1
cn.com.my.test2=test2

1、@Value注解

这种方式是spring最早提供的方式,通过@Value注解的方式,该注解用在属性上,但是要求该属性所在的类必须要被spring管理。

package com.example.demo.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody; @Controller
public class TestController { @Value("${cn.com.my.test1}")
private String test1;
@Value("${cn.com.my.test2}")
private String test2; @RequestMapping("/test1/test")
@ResponseBody
public String getTest(){
return "hello:"+test1+",test2:"+test2;
} }

在标记有@Controller类中使用了带有@Value注解的test1和test2的属性,首先标记有@Controller注解便可以使该类被spring管理。其次,使用@Value标记了属性,则可以获得application.properties(application.yml)文件中的属性,这里使用${cn.com.my.test1},属性的名称必须是全部的名称,测试结果如下,

2、@ConfigurationProperties

@ConfigurationProperties注解是springboot提供的,在springboot中大量使用,下面看其用法,

使用@Component注解

这里需要定义一个类,

package com.example.demo.properties;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component; @Component
@ConfigurationProperties(prefix = "cn.com.my")
public class ApplicationPro {
private String test1;
private String test2;
private String testName; //必须有set方法
public void setTest1(String test1) {
this.test1 = test1;
} //必须有set方法
public void setTest2(String test2) {
this.test2 = test2;
} public String getTest1() {
return test1;
} public String getTest2() {
return test2;
}
public void setTestName(String testName) {
this.testName = testName;
}

public String getTestName() {
return testName;
}
}

该类上使用了@ConfigurationProperties注解,且配置了prefix属性,指定了要获取属性的前缀,这里的前缀是cn.com.my,在类中定义的属性名最好和application.properties文件中的一致,不过这种方式可以采用稀疏匹配,把application.properties修改为下面的内容,

cn.com.my.test1=test1
cn.com.my.test2=test2
cn.com.my.test-name="hello world"

另外,在ApplicationPro类上标记有@Component注解,标记该注解的意思是要把该类交给spring管理,也就是说要让spring管理此类,其实也可以使用其他注解,如,@Service等

下面看测试类,

package com.example.demo.controller;

import com.example.demo.properties.ApplicationPro;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody; @Controller
public class TestController3 {
@Autowired
private ApplicationPro ap;
@RequestMapping("test3/test")
@ResponseBody
public String getTest(){
return ap.getTest1()+","+ap.getTest2()+","+ap.getTestName();
}
}

看测试结果,

从上面的结果可以看出已经获得了application.properties文件中的值,并且获得了test-name的值。具体匹配规则可以自行百度,这里强烈建议配置文件中的属性和类中的保持一致。

使用@EnableConfigurationProperties注解

使用该注解在ApplicationPro类中便不需要使用@Component注解,

package com.example.demo.properties;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component; //@Component
@ConfigurationProperties(prefix = "cn.com.my")
public class ApplicationPro {
private String test1;
private String test2;
private String testName; //必须有set方法
public void setTest1(String test1) {
this.test1 = test1;
} //必须有set方法
public void setTest2(String test2) {
this.test2 = test2;
} public String getTest1() {
return test1;
} public String getTest2() {
return test2;
} public void setTestName(String testName) {
this.testName = testName;
} public String getTestName() {
return testName;
}
}

再看启动类,在启动类上标记了@EnableConfigurationProperties({ApplicationPro.class}),也就是使@ConfigurationProperties注解生效,并标记了标有@ConfigurationProperties注解的类Application.class

package com.example.demo;

import com.example.demo.properties.ApplicationPro;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties; @SpringBootApplication
@EnableConfigurationProperties({ApplicationPro.class})
public class DemoApplication { public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
} }

下面看测试结果,

3、Environment对象

使用Environment对象,该对象是spring提供的一个对象,且是spring内部创建的对象,

package com.example.demo.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody; @Controller
public class TestController2 {
@Autowired
private Environment environment; @RequestMapping("/test2/test")
@ResponseBody
public String getTest(){
return "hello,"+environment.getProperty("cn.com.my.test1")+","+"test2:"+environment.getProperty("cn.com.my.test2");
}
}

可以看到,可以直接注入该对象的实例,通过其getProperty方法获得相应的属性值。

三、总结

本文总结了,在使用springboot的过程中获取配置文件中的几种方式,

@Value

@ConfigurationProperties

Environment对象

有不当之处,欢迎指正,谢谢。

springboot:读取application.yml文件的更多相关文章

  1. SpringBoot读取application.properties文件

    http://blog.csdn.net/cloume/article/details/52538626 Spring Boot中使用自定义的properties Spring Boot的applic ...

  2. SpringBoot读取application.properties文件内容

    application.properties存储数据的方式是key-value. application.properties内容 userManager.userFile=data/user.pro ...

  3. SpringBoot(十):读取application.yml下配置参数信息,java -jar启动时项目修改参数

    读取application.yml下配置参数信息 在application.yml文件内容 my: remote-address: 192.168.1.1 yarn: weburl: http://1 ...

  4. SpringBoot读取Resource下文件的几种方式(十五)

    需求:提供接口下载resources目录下的模板文件,(或者读取resources下的文件)给后续批量导入数据提供模板文件. 方式一:ClassPathResource //获取模板文件:注意此处需要 ...

  5. 【2.0】SpringBoot多环境yml文件配置

    一.使用Spring Boot Profiles 1. 使用yml文件 首先,我们先创建一个名为 application.yml的属性文件,如下: server: port: 8080 my: nam ...

  6. Spring Boot中application.properties和application.yml文件

    application.properties和application.yml文件可以放在一下四个位置: 外置,在相对于应用程序运行目录的/congfig子目录里. 外置,在应用程序运行的目录里 内置, ...

  7. Spring Boot项目application.yml文件数据库配置密码加密

    在Spring boot开发中,需要在application.yml文件里配置数据库的连接信息,或者在启动时传入数据库密码,如果不加密,传明文,数据库就直接暴露了,相当于"裸奔"了 ...

  8. springboot加载application.yml文件null

    话不多说,直接上代码 本人项目为maven项目 以下是项目结构 pom.xml文件 <?xml version="1.0" encoding="UTF-8" ...

  9. SpringBoot 从application.yml中通过@Value读取不到属性值

    package cn.exrick.xboot.mqtt; import org.eclipse.paho.client.mqttv3.*;import org.eclipse.paho.client ...

随机推荐

  1. JS数组去重的9种方法(包括去重NaN和复杂数组类型)

    其实网上已经有很多js数组的去重方法,但是我看了很多篇并自己通过代码验证,发现都有一些缺陷,于是在研究多篇代码之后,自己总结了9种方法,如果有哪里不对请及时纠正我哈~ 转载请表明出处 测试代码 let ...

  2. os00

    - 运行状态:占用处理机资源运行,处于此状态的进程数小于等于CPU数# 操作系统* 进程和线程    * [进程和线程有什么区别?](#进程和线程有什么区别)    * [进程间通信有哪些方式?](# ...

  3. 准备数据集用于flink学习

    欢迎访问我的GitHub https://github.com/zq2599/blog_demos 内容:所有原创文章分类汇总及配套源码,涉及Java.Docker.Kubernetes.DevOPS ...

  4. 在一个递增数组的rotate变换中找target

    Search in Rotated Sorted Array Suppose an array sorted in ascending order is rotated at some pivot u ...

  5. 《GNU_makefile》第五章——为规则书写命令

    1. 使用make的命令行参数-n或--just-print,make会只显示要执行的命令,不执行,这样方便调试makefile. 2.执行命令 每写一行命令,make会fork出一个shell进程来 ...

  6. IIC、SPI、UART协议总结

    IIC 特点 1.Inter-Integrated Circuit,内部集成总线,半双工 2.短距离传输,有应答,速度较慢 3.SDA双向数据线,SCL时钟线 4.可以挂载多个设备,IIC设备有固化地 ...

  7. linux开机启动及运行级别、root密码丢失、单用户模式只读的处理方法

    linux系统启动大致步骤如下:  加电自检-->根据BIOS中的设置从指定的设备启动-->找到设备MBR中的bootloader引导启动系统-->启动kernel-->启动i ...

  8. async await 你真的用对了吗?

    大部分同学了解Promise,也知道async await可以实现同步化写法,但实际上对一些细节没有理解到位,就容易导致实际项目中遇到问题. 开始先抛结论,下文将针对主要问题点进行论述. 1.所有as ...

  9. Python_列表相减(判断长度后长的减短的)

    #定义一个方法,可进行列表相减 class V(object): def __init__(self,*value): self.value=value def __sub__(self,other) ...

  10. LeetCode283移动零问题java高效解法

    一.题目: 给定一个数组 nums,编写一个函数将所有 0 移动到数组的末尾,同时保持非零元素的相对顺序. 示例: 输入: [0,1,0,3,12] 输出: [1,3,12,0,0] 说明: 1.必须 ...