@ConfigurationProperties给自定义的属性赋值不成功的原因

@ConfigurationProperties给自定义的属性赋值不成功的原因

YML配置文件中的内容

aliyun:
  oss:
    file:
      endpoint: oss-cn-hangzhou
      keyid: 7878
      keysecret: 43566768
      bucketname: a great

读取配置文件的类:

@Component
@ConfigurationProperties(prefix = "aliyun.oss.file")
public class ConstantYmlUtils implements InitializingBean {

    // @Value("${aliyun.oss.file.endpoint}")
    private String endpoint;

    // @Value("${aliyun.oss.file.keyid}")
    private String keyid;

    // @Value("${aliyun.oss.file.keysecret}")
    private String keysecret;

    // @Value("${aliyun.oss.file.bucketname}")
    private String bucketname;

    public static String OSSENDPOINT;
    public static String OSSKEYID;
    public static String OSSKEYSECRET;
    public static String OSSBUCKETNAME;

    @Override
    public void afterPropertiesSet() throws Exception {
        OSSENDPOINT = endpoint;
        OSSKEYID = keyid;
        OSSKEYSECRET = keysecret;
        OSSBUCKETNAME = bucketname;
    }

}

测试过程中并没有读取成功,而我配置的属性值和前缀都和YML文件中的信息匹配
未成功匹配的原因:没有给属性值加添get和set方法,添加后,复制成功

@ConfigurationProperties是Spring框架中的一个注解,用于将配置文件中的属性值绑定到Java对象上。当我们需要使用Map属性接收配置文件中的属性时,可以通过以下步骤实现: 1. 创建一个Java类,用于接收配置文件中的属性值,并使用@ConfigurationProperties注解标注该类。 2. 在该类中定义一个Map类型的属性,并提供对应的getter和setter方法。 3. 在配置文件中,使用"prefix.key=value"的格式来设置Map属性的值。 下面是一个示例代码: ```java import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.stereotype.Component; import java.util.Map; @Component @ConfigurationProperties(prefix = "example") public class ExampleProperties { private Map<String, String> mapProperty; public Map<String, String> getMapProperty() { return mapProperty; } public void setMapProperty(Map<String, String> mapProperty) { this.mapProperty = mapProperty; } } ``` 在上述示例中,我们使用@ConfigurationProperties注解将ExampleProperties类标记为一个配置类,并通过prefix属性指定了配置文件中属性的前缀为"example"。然后,我们定义了一个名为mapProperty的Map类型属性,并提供了对应的getter和setter方法。 在配置文件(例如application.properties)中,我们可以使用以下方式设置Map属性的值: ```properties example.mapProperty.key1=value1 example.mapProperty.key2=value2 ``` 这样,Spring框架会自动将配置文件中的属性值绑定到ExampleProperties类的mapProperty属性上。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

王野也不野

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

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

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

打赏作者

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

抵扣说明:

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

余额充值