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

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

@Value注解

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

java 复制代码
public class Demo1{
    @Value("${url}")
    private String url;

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

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

java 复制代码
    @Value("${publish.id.array}")
    private int[] publishId;

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

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

本地变量给了默认值。

java 复制代码
    @Value("${url:http://wuai.test1.com}")
    private String url;

yml给了默认值。

java 复制代码
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 对象。如,

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 对象。

java 复制代码
@Component
@ConfigurationProperties(prefix = "event.listener")
public class EventListenerConfig {

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

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

java 复制代码
@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;
    
    }
    
}
相关推荐
程序员黑豆7 小时前
Java 注释详解:单行、多行与文档注释的完整指南
java·前端·ai编程
hey_sml8 小时前
JAVA每日一学---CompletableFuture中thenApply与thenCompose区别详解
java·开发语言
Doraemomo8 小时前
数据结构-环形链表
java·数据结构·链表
维克兜率天9 小时前
【维克】ARMA模型:AR与MA的完美结合
后端·restful
萧瑟余晖9 小时前
Java深入解析篇十七之SpringCloud
java·开发语言
是未才10 小时前
从输入 URL 到页面返回:DNS、路由、TLS 与 HTTP 完整链路
java·后端·计算机网络
上海安当技术10 小时前
半天接入:USBKey RESTful API + C 动态库,Web 和 C/S 两套集成路径实战
前端·后端·restful·集成·usbkey
ttod_qzstudio10 小时前
Java 常用语法极简通关(五):类与对象——字段、方法、构造器、this 与 static
java·开发语言·python
DevUI团队11 小时前
从“即兴创作”到“规格先行”,华为云码道(CodeArts)代码智能体持续深耕企业级规范驱动开发能力
前端·人工智能·后端
萧瑟余晖11 小时前
Java深入解析篇十七之Spring Security
java·开发语言·spring