@PropertySource 的详细介绍

@PropertySource 的详细介绍

功能

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

  • @PropertySource 和 @Value 组合使用,可以将配置文件中的属性值注入到当前类的使用 @Value 注解的成员变量中。
  • @PropertySource 和 @ConfigurationProperties 组合使用,可以将配置文件与 Java 类绑定,使用 prefix 指定统一前缀,将配置文件中的属性值与该 Java 类的成员变量一一比较赋值,如果某个变量在配置文件中找不到,会自动赋空(null)。

源码

package org.springframework.context.annotation;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Repeatable;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

import org.springframework.core.io.support.PropertySourceFactory;

@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;
}

使用示例

属性文件:zyc-test.properties

zyc.test.id=1
zyc.test.name=blueribbon
zyc.test.age=23

示例一:@PropertySource + @Value

@Data
@Component
@PropertySource("classpath:zyc-test.properties")
public class ChildWithValue {

    @Value("${zyc.test.id}")
    private Integer id;
    @Value("${zyc.test.name}")
    private String name;
    @Value("${zyc.test.age}")
    private Integer age;
}

示例二:@PropertySource 和 @ConfigurationProperties

@Data
@Component
@PropertySource("classpath:zyc-test.properties")
@ConfigurationProperties(prefix = "zyc.test")
public class ChildWithConfigurationProperties {

    private Integer id;
    private String name;
    private Integer age;
}

示例测试

@Slf4j
@Component
public class CommandRunner implements CommandLineRunner {

    @Autowired
    ChildWithValue childWithValue;

    @Autowired
    ChildWithConfigurationProperties childWithConfigurationProperties;

    @Override
    public void run(String... args) throws Exception {
        log.info("使用@PropertySource和@Value给属性赋值:{}", childWithValue.toString());
        log.info("使用@PropertySource和@ConfigurationProperties:{}", childWithConfigurationProperties.toString());
    }
}

启动项目查看打印结果。
在这里插入图片描述

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

蓝带915

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值