官方描述:
描述
@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则抛出a。
注:该@PropertySource注释是可重复的,根据Java的8约定。但是,所有这些@PropertySource注释都需要在同一级别声明,可以直接在配置类上声明,也可以在同一自定义注释中作为元注释声明。不建议混合直接注释和元注释,因为直接注释有效地覆盖了元注释。