まず、カスタム設定ファイルをロードします。
1、application.ymlの家族に新しいfamily.yamファイルを、コピーされたオブジェクト
家族: 家族 - 名前: DAD: 名前:レヴィ 年齢: 30 {。#$ランダムの整数}乱数の値を送信することができませんされて :MOM :エイリアス - yilisha - ALISE 年齢:$ {#}母family.dad.ageを同じ年齢と私の父ではなく、デフォルトは24歳で 子供: 名前:happlyboy 年齢: 5人の 友達: - {趣味:野球、性別:男性} - {趣味:サッカー、セックス:famale}
2、カスタム設定クラス:
パッケージcom.liyu.helloworld.config。 輸入org.springframework.beans.factory.config.YamlPropertiesFactoryBean; 輸入org.springframework.core.env.PropertiesPropertySource。 輸入org.springframework.core.env.PropertySource。 輸入org.springframework.core.io.support.DefaultPropertySourceFactory。 輸入org.springframework.core.io.support.EncodedResource。 インポートにjava.io.IOException; 輸入java.util.Properties; パブリック クラス MixPropertySourceFactoryは延びDefaultPropertySourceFactory { 公開PropertySource <?> createPropertySource(文字列名、EncodedResourceリソース)がスローにIOException { 文字列またはsourceName =名前を!= nullの?名前:resource.getResource()getFilename();。 もし(!。resource.getResource()が存在する()){ 返す 新しい PropertiesPropertySourceを(またはsourceName、新しいプロパティ()); } そう であれば(sourceName.endsWith( "YML。 ")|| sourceName.endsWith(" YAML。" )){ プロパティpropertiesFromYaml = loadYml(リソース) 返す 新しいですPropertiesPropertySource(またはsourceName、propertiesFromYaml)。 } 他{ 戻り スーパー.createPropertySource(名前、リソース)。 } } プライベートプロパティloadYml(EncodedResourceリソース)スローのIOException { YamlPropertiesFactoryBean工場 = 新しいYamlPropertiesFactoryBean()。 factory.setResources(resource.getResource())。 factory.afterPropertiesSet(); リターンfactory.getObject(); } }
この設定は、デフォルトspringbootのapplication.propertiesファイルに加えて導入するだけでなく、カスタムファイルYMLの導入が可能
@PropertySource(値= { "クラスパス:family.yml"}。、工場= MixPropertySourceFactory クラス) パブリック クラスファミリー{
それだけで追加し、コンフィギュレーション・ファイルのプロパティを読み取ることであれば、家族のカテゴリに注釈を加えた@PropertySource(value = {"classpath:family.properties"})
に。いいえ定義MixPropertySourceFactoryません。
優先順位のアプリケーション構成ファイルがはるかに高い優先順位は、同じプロパティで構成され、唯一のワードアプリケーションを有効にするには、平均よりYMLプロファイル構成されていませんされています
第二に、古い設定ファイル(XMLファイル)を導入
1、カスタムXML設定ファイル
<?= "1.0"エンコード= "UTF-8" XMLバージョン?> < 豆のxmlns = "http://www.springframework.org/schema/beans" のxmlns:XSI = "http://www.w3.org/2001 / XMLスキーマ・インスタンス" のxsi:のschemaLocation = "http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd" > < ビーンID =" testBeanService " クラス=" com.liyu.helloworld.service.TestBeanService」> </ 豆> </ 豆>
2、時にロードされたスタートアップコンフィギュレーションXMLファイルspringboot
@SpringBootApplication
@ImportResource(位置= { "クラスパス:beans.xmlの"})
パブリッククラスBoot01HelloworldApplication {
パブリック静的無効メイン(文字列[] args){
SpringApplication.run(Boot01HelloworldApplication.class、引数)。
}
}
3、テストクラスを作成します。
@RunWith(SpringRunner.class)
@SpringBootTest
パブリッククラスTestBean {
@Autowired
プライベートConfigurableApplicationContext IOC;
@Test
公共ボイドtestHelloService(){
効果取るがtestBeanServiceは、豆、任意の表現XML構成ファイルかどうか//試験Springコンテキスト
ブール= ioc.containsBean testBeanService( "testBeanService");
のSystem.out.println(testBeanService);
}
}
4、結果:
スプリングは、ターゲットBeanに注入しました