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;
    
    }
    
}
相关推荐
花椒技术43 分钟前
企业内部 Agent 落地复盘:Gateway、Skill 和二次确认如何串起受控业务执行
后端·agent·ai编程
REDcker2 小时前
Linux OverlayFS详解
java·linux·运维
Royzst2 小时前
xml知识点
java·服务器·前端
我是一颗柠檬3 小时前
【MySQL全面教学】MySQL事务与ACID Day9(2026年)
数据库·后端·mysql
枕星而眠3 小时前
数据结构八大排序详解(一):四大简单排序
c语言·数据结构·c++·后端
IT_陈寒3 小时前
React useEffect闭包陷阱差点把我整失业了
前端·人工智能·后端
鱼鳞_3 小时前
苍穹外卖-Day08(缓存套餐)
java·redis·缓存
过期动态3 小时前
【LeetCode 热题 100】移动零
java·数据结构·算法·leetcode·职场和发展·rabbitmq
苍何3 小时前
爆肝两周,我把 Codex 最全实战指南开源了
后端
苏渡苇3 小时前
服务容错的必要性与Spring Cloud Alibaba Sentinel 限流配置实战
spring boot·spring cloud·sentinel