@PropertySource注解为向 Spring 的环境(Environment)添加 PropertySource 提供了一种方便的声明性机制。
给定一个包含键值对 testbean.name=myTestBean的名为 app.properties的文件,下面的@Configuration类以这样一种方式使用 @PropertySource,即调用 testBean.getName()返回 myTestBean:
@Configuration@PropertySource("classpath:/com/myco/app.properties")public class AppConfig {@AutowiredEnvironment env;@Beanpublic 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 {@AutowiredEnvironment env;@Beanpublic TestBean testBean() {TestBean testBean = new TestBean();testBean.setName(env.getProperty("testbean.name"));return testBean;}}
假设 my.placeholder存在于一个已经注册的属性源中(例如,系统属性或环境变量),那么该占位符将被解析为相应的值。如果没有,那么就使用 default/path作为默认值。如果没有指定默认值,并且一个属性不能被解析,就会抛出一个 IllegalArgumentException。
:::info 根据 Java 8 惯例,@PropertySource 注解是可重复的。然而,所有这些 @PropertySource 注解都需要在同一级别上声明,要么直接在配置类上声明,要么作为同一自定义注解中的元注解。不建议混合使用直接注解和元注解,因为直接注解会有效地覆盖元注解。 :::
