@ConfigurationProperties与@Value进行属性的注入
发布日期:2021-05-07 13:36:01 浏览次数:27 分类:精选文章

本文共 2160 字,大约阅读时间需要 7 分钟。

Spring Boot 中的 @ConfigurationProperties 和 @Value 注解

在开发 Spring Boot 应用程序时,配置管理是核心任务之一。@ConfigurationProperties 和 @Value 注解为我们提供了简便的方式来处理配置文件和注入值。本文将详细介绍这两个注解的使用方法和场景。

@ConfigurationProperties 注解

@ConfigurationProperties 是 Spring Boot 特有的注解,用于将属性文件中的值注入到类中的属性字段中。这种注解非常有用,特别是在处理大型配置文件时。

使用场景

假设你的 application.properties 文件中有 Redis 配置如下:

redis.config.maxTotal=5000
redis.config.maxIdle=10
redis.config.maxWaitMillis=5000
redis.config.testWhileIdle=true
redis.config.numTestsPerEvictionRun=100
redis.config.timeBetweenEvictionRunsMillis=6000
redis.config.testOnBorrow=true
redis.config.testOnReturn=true
redis.config.host=127.0.0.1
redis.config.port=6379
redis.config.name=localhost_redis
redis.config.timeout=5000
redis.config.weight=1
redis.config.password=XXX

在定义的 Redis 配置类中,可以使用 @ConfigurationProperties 注解来自动注入这些属性:

@Configuration
@ConfigurationProperties(prefix = "redis.config")
@Data
public class RedisConfiguration {
private int maxTotal;
private int maxIdle;
private int maxWaitMillis;
private boolean testWhileIdle;
private int numTestsPerEvictionRun;
private int timeBetweenEvictionRunsMillis;
private boolean testOnBorrow;
private boolean testOnReturn;
private String host;
private String name;
private int port;
private int timeout;
private int weight;
private String password;
}

注意事项

  • prefix 属性:@ConfigurationProperties 注解的 prefix 属性用于指定属性文件的前缀。例如,上述例子中,所有属性都以 "redis.config" 作为前缀。

  • @Value 注解:除了使用 @ConfigurationProperties,你还可以选择使用 @Value 注解直接注入特定属性。例如:

    @Value("${spring.redis.weight}")
    private int weight;

@Value 注解

@Value 注解是另一种常用的注入方式,可以用来注入各种类型的值,包括字符串、系统属性、表达式结果、文件内容等。

常见注入类型

  • 普通字符串:直接注入字符串值。
  • 操作系统属性:通过 @Value("${system.property}") 注入操作系统属性。
  • 表达式运算:支持使用 SpEL 表达式进行动态计算。
  • 其他 Bean 属性:可以注入其他 Bean 的属性。
  • 文件内容:支持读取文件内容并注入。
  • 网址信息:常用于注入 URL、IP 地址等。
  • 属性文件:类似 @ConfigurationProperties,但通常用于单个属性或特定路径下的属性。

示例

以下是一个使用 @Value 注解的示例:

@Value("http://example.com")
private String serverUrl;

或者通过 SpEL 表达式:

@Value("#{2*3}")
private int result;

总结

在 Spring Boot 应用中,@ConfigurationProperties 和 @Value 注解为我们提供了灵活的配置管理方式。@ConfigurationProperties 适用于批量注入属性文件中的多个属性,而 @Value 则适用于单个值或复杂表达式的注入。合理选择适合的注解,使您的代码更加简洁和高效。

上一篇:一条SQL查询是如何执行的
下一篇:Java并发编程实战:闭锁CountDownLatch,栅栏CyclicBarrier与信号量Semaphore

发表评论

最新留言

路过,博主的博客真漂亮。。
[***.116.15.85]2025年03月16日 17时16分49秒