spring中@PropertySource详解

官方描述:

https://docs.spring.io/spring/docs/5.1.7.RELEASE/spring-framework-reference/core.html#beans-using-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则抛出a。

注:该@PropertySource注释是可重复的,根据Java的8约定。但是,所有这些@PropertySource注释都需要在同一级别声明,可以直接在配置类上声明,也可以在同一自定义注释中作为元注释声明。不建议混合直接注释和元注释,因为直接注释有效地覆盖了元注释。

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值