@PropertySource使用

功能

加载指定的属性文件(*.properties)到 Spring 的 Environment 中。可以配合 @Value 和 @ConfigurationProperties 使用。

  • @PropertySource 和 @Value 组合使用,可以将自定义属性文件中的属性变量值注入到当前类的使用@Value注解的成员变量中。

  • @PropertySource 和 @ConfigurationProperties 组合使用,可以将属性文件与一个Java类绑定,将属性文件中的变量值注入到该Java类的成员变量中。

源码

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Repeatable(PropertySources.class)
public @interface PropertySource {
    /**
     * 属性源的名称
     */
    String name() default "";

    /**
     * 属性文件的存放路径
     */
    String[] value();
    
    /**
     * 如果指定的属性源不存在,是否要忽略这个错误
     */
    boolean ignoreResourceNotFound() default false;

    /**
     * 属性源的编码格式
     */
    String encoding() default "";
    
    /**
     * 属性源工厂
     */
    Class<? extends PropertySourceFactory> factory() default PropertySourceFactory.class;

}

使用示例

属性文件:demo.properties

demo.name=huang
demo.sex=1
demo.type=demo

示例一:@PropertySource + @Value

@Component
@PropertySource(value = {"demo/props/demo.properties"})
public class ReadByPropertySourceAndValue {
    @Value("${demo.name}")
    private String name;

    @Value("${demo.sex}")
    private int sex;

    @Value("${demo.type}")
    private String type;
    
    @Override
    public String toString() {
        return "ReadByPropertySourceAndValue{" +
                "name='" + name + '\'' +
                ", sex=" + sex +
                ", type='" + type + '\'' +
                '}';
    }
}

示例二:@PropertySource 和 @ConfigurationProperties

@Component
@PropertySource(value = {"demo/props/demo.properties"})
@ConfigurationProperties(prefix = "demo")
public class ReadByPropertySourceAndConfProperties {
    private String name;
    private int sex;
    private String type;
    
    //getter和setter

    @Override
    public String toString() {
        return "ReadByPropertySourceAndConfProperties{" +
                "name='" + name + '\'' +
                ", sex=" + sex +
                ", type='" + type + '\'' +
                '}';
    }
}    
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值