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

原文地址:https://www.cnblogs.com/dalianpai/p/13679365.html