ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

Spring的PropertySource注解

2020-09-16 15:35:25  阅读:236  来源: 互联网

标签:PropertySource resource stream Spring reader 注解 TestBean testBean


使用@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

标签:PropertySource,resource,stream,Spring,reader,注解,TestBean,testBean
来源: https://www.cnblogs.com/dalianpai/p/13679365.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有