Spring Boot 注解探秘:常用配置值读取注解的魔力

在 Spring Boot 应用开发中,我们会常常借助Apollo,Spring Cloud Config等配置中心来集中管理配置信息,在拥有配置信息之后,高效且准确地读取这些配置信息无疑是极为关键的一环。今天我们就来介绍几个常用的用于配置值读取的注解。

@Value注解

@Value注解是 Spring 中一种非常方便的用于注入配置值的方式,支持基本数据类型。

public class Demo1{
    @Value("${url}")
    private String url;

    @Value("${gray.switch:true}")
    private boolean graySwitch;
   
}

也支持数组以及列表类型。

    @Value("${publish.id.array}")
    private int[] publishId;

    @Value("${employee.list}")
    private List<String> employee;

这里补充一种场景,假如apollo服务端配置了key为url,  value为http://wuai.test.com。

本地变量给了默认值。

    @Value("${url:http://wuai.test1.com}")
    private String url;

yml给了默认值。

url: "http://wuai.test2.com"

那么在应用启动的时候读取的url的值是哪个呢? http://wuai.test.com。

如果服务端配置没有url,那么读取到的url是http://wuai.test1.com。本地变量没有默认值,读取到的url是http://wuai.test2.com

@ApolloJsonValue注解

@ApolloJsonValue是一个特定于 Apollo 配置中心的注解,它主要用于从 Apollo 配置中心读取以 JSON 格式存储的配置内容,并将其自动反序列化为 Java 对象。如,

public class User{
    private String name;
    private String sex;
    private Integer age;
}

public class Demo2{
    @ApolloJsonValue("${user.config}")
    private User user;
}

以下是apollo配置。

@ConfigurationProperties 注解

@ConfigurationProperties注解是一个非常有用的工具,常用于将外部配置属性绑定到 Java 对象。

@Component
@ConfigurationProperties(prefix = "event.listener")
public class EventListenerConfig {

    private boolean enable;
    
    private List<String> events;
    
}

@ConfigurationProperties注解还支持嵌套对象,如。

@Component
@ConfigurationProperties(prefix = "event")
public class EventConfig {

    private Object obj;

    @Component
    @ConfigurationProperties(prefix = "event.teller")
    public class EventTellerConfig {

        private boolean enable;
        
        private List<String> events;
    
    }
    
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值