标签: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
。
查看源码:
会发现源码中,是4.3版本才有的,假如讲到4.3以下要添加以下才能解析properties文件。
@Bean
public static PropertySourcesPlaceholderConfigurer createPropertySourcesPlaceholderConfigurer(){
return new PropertySourcesPlaceholderConfigurer();
}
点进去查看源码
2个参数的够用
一个参数的构造
到最后实现的构造方法
加载配置文件的方法
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. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。