黄色电影一区二区,韩国少妇自慰A片免费看,精品人妻少妇一级毛片免费蜜桃AV按摩师 ,超碰 香蕉

SpringBoot讀取yml文件有哪幾種方式

springboot讀取yml文件有哪幾種方式

本文講解"springboot讀取yml文件有哪幾種方式",希望能夠解決相關(guān)問題。


spring boot讀取yml文件的主要方式有以下幾種:

1.@value注解

我們可以在bean的屬性上使用@value注解,直接讀取yml中的值,如:

application.yml:

name:?zhangsan

bean:

public?class?mybean?{
????@value("${name}")
????private?string?name;
}

2.environment對(duì)象

我們可以通過注入environment對(duì)象來讀取yml值,如:

@autowired
private?environment?environment;
public?void?dosomething()?{
????string?name?=?environment.getproperty("name");
}

3.@configurationproperties注解

我們可以使用@configurationproperties注解將yml中的值映射到bean的屬性上,如:

application.yml:

my:?
????name:?zhangsan
????age:?18

bean:

@component?
@configurationproperties(prefix?=?"my")
public?class?myprops?{
????private?string?name;
????private?int?age;
????//?getter?and?setter
}

4.ymlpropertysourcefactory

我們可以使用ymlpropertysourcefactory來加載yml文件,然后像普通properties一樣讀取值,如:

@bean
public?static?propertysourcesplaceholderconfigurer?properties()?{
????yamlpropertiesfactorybean?factory?=?new?yamlpropertiesfactorybean();
????factory.setresources(new?classpathresource("application.yml"));
????factory.getobject().foreach((k,?v)?->?system.out.println(k?+?":?"?+?v));
????return?factory;?
}

5.@yamlcomponent注解

如果yml文件中用—分隔了多個(gè)文檔,我們可以使用@yamlcomponent注解將每份文檔映射到一個(gè)bean上,如:

application.yml:

my:
??name:?zhangsan?
---
my:?
??name:?lisi

beans:

@component("first")?
@yamlcomponent(value?=?"my.first")
public?class?firstprops?{
????private?string?name;
}
@component("second")??
@yamlcomponent(value?=?"my.second")
public?class?secondprops?{
????private?string?name;?
}

這就是spring boot讀取yml文件的主要5種方式,可以根據(jù)需要選擇使用。yml作為spring boot默認(rèn)的配置文件格式,理解如何操縱yml文件將有助于我們實(shí)現(xiàn)系統(tǒng)配置的靈活性。

關(guān)于 "springboot讀取yml文件有哪幾種方式" 就介紹到此。希望多多支持碩編程。

下一節(jié):java的預(yù)定義class對(duì)象的方法

java編程技術(shù)

相關(guān)文章