SPRINGBOOT读取PROPERTIES配置文件数据过程详解

时间:2021-05-20

这篇文章主要介绍了SPRINGBOOT读取PROPERTIES配置文件数据过程详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

一.使用@ConfigurationProperties来读取

1、Coffer entity

@Configuration@ConfigurationProperties(prefix = "coffer")@PropertySource("classpath:config/coffer.properties")public class Coffer { private String brand; private Double length; private Double width; private Double height; //省略了get/set方法 private String[] contains; private ArrayList<Fruit> fruits; private HashMap<String,Object> map;}

2、Fruit entity

@Configuration@ConfigurationProperties(prefix = "coffer.fruits")@PropertySource("classpath:config/coffer.properties")public class Fruit { private String fruitName; private String fruitColor; //省略了get/set方法 }

3、coffer.properties

coffer.brand=Camelcoffer.length=100.00coffer.width=80.00coffer.height=60.00coffer.contains[0]=Raincoatcoffer.contains[1]=trouserscoffer.contains[2]=hatcoffer.contains[3]=glovecoffer.contains[4]=scarfcoffer.contains[5]=hoodcoffer.fruits[0].fruitName=apricotcoffer.fruits[0].fruitColor=yellowcoffer.fruits[1].fruitName=plumcoffer.fruits[1].fruitColor=greencoffer.fruits[2].fruitName=pineapplecoffer.fruits[2].fruitColor=yellowcoffer.fruits[3].fruitName=watermeloncoffer.fruits[3].fruitColor=greencoffer.fruits[4].fruitName=strawberrycoffer.fruits[4].fruitColor=redcoffer.map.name=xiaomaocoffer.map.age=22coffer.map.gender=female

4、springbootApplicationTest

@SpringBootTestclass SpringbootApplicationTests { @Autowired private ApplicationContext ioc; @Autowired private Coffer coffer; @Test public void springbootTest(){ System.out.println(coffer); }}

5、result

Coffer{  brand='Camel',   length=100.0,   width=80.0,   height=60.0,   contains=[Raincoat, trousers, hat, glove, scarf, hood],   fruits=[       Fruit{fruitName='apricot', fruitColor='yellow'},        Fruit{fruitName='plum', fruitColor='green'},        Fruit{fruitName='pineapple', fruitColor='yellow'},        Fruit{fruitName='watermelon', fruitColor='green'},        Fruit{fruitName='strawberry', fruitColor='red'}      ],   map={age=22, gender=female, name=xiaomao}}

二、使用@Value来读取

在springTest中无法使用@Value来读取配置属性,需要放到Controller中去读取

@PropertySource("classpath:config/coffer.properties")@RestControllerpublic class SpringbootController { @Value("${coffer.brand}") private String brand; @Value("${coffer.height}") private Double height; @RequestMapping("/test") public String springbootTest() { return brand+"====="+height; }}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。

相关文章