Spring的PropertySource注解


使用@PropertySource

@PropertySource 為將PropertySource添加到 Spring 的Environment提供了一種方便的聲明性機制。

給定名為app.properties的文件,其中包含鍵值對testbean.name=myTestBean,以下@Configuration類使用@PropertySource,從而對testBean.getName()的調用返回myTestBean

@Configuration
@PropertySource("classpath:/com/myco/app.properties")
public class AppConfig {

    @Autowired
    Environment env;

    @Bean
    public TestBean testBean() {
        TestBean testBean = new TestBean();
        testBean.setName(env.getProperty("testbean.name"));
        return testBean;
    }
}

@PropertySource資源位置中存在的任何${…}占位符都是根據已針對該環境注冊的一組屬性源來解析的,如以下示例所示:

@Configuration
@PropertySource("classpath:/com/${my.placeholder:default/path}/app.properties")
public class AppConfig {

    @Autowired
    Environment env;

    @Bean
    public TestBean testBean() {
        TestBean testBean = new TestBean();
        testBean.setName(env.getProperty("testbean.name"));
        return testBean;
    }
}

假定my.placeholder存在於已注冊的屬性源之一(例如,系統屬性或環境變量)中,則占位符將解析為相應的值。如果不是,則使用default/path作為默認值。如果未指定默認值並且無法解析屬性,則會引發IllegalArgumentException

查看源碼:

image-20200916144157787

會發現源碼中,是4.3版本才有的,假如講到4.3以下要添加以下才能解析properties文件。

    @Bean
    public static PropertySourcesPlaceholderConfigurer createPropertySourcesPlaceholderConfigurer(){
        return new PropertySourcesPlaceholderConfigurer();
    }

點進去查看源碼

image-20200916145054684

2個參數的夠用

image-20200916145115160

一個參數的構造

image-20200916150937737

到最后實現的構造方法

image-20200916145446483

加載配置文件的方法

	static void fillProperties(Properties props, EncodedResource resource, PropertiesPersister persister)
			throws IOException {

		InputStream stream = null;
		Reader reader = null;
		try {
			String filename = resource.getResource().getFilename();
			if (filename != null && filename.endsWith(XML_FILE_EXTENSION)) {
				stream = resource.getInputStream();
				persister.loadFromXml(props, stream);
			}
			else if (resource.requiresReader()) {
				reader = resource.getReader();
				persister.load(props, reader);
			}
			else {
				stream = resource.getInputStream();
				persister.load(props, stream);
			}
		}
		finally {
			if (stream != null) {
				stream.close();
			}
			if (reader != null) {
				reader.close();
			}
		}
	}

看上面源碼是支持xml的,下面在詳細寫一下解析xml和yml


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM