今天就跟大家聊聊有关如何理解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; }}
看完上述内容,你们对如何理解SPRINGBOOT读取PROPERTIES配置文件数据过程有进一步的了解吗?如果还想了解更多知识或者相关内容,请关注亿速云行业资讯频道,感谢大家的支持。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。